wxgui.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. """!
  2. @package wxgui.py
  3. @brief Main Python app for GRASS wxPython GUI. Main menu, layer management
  4. toolbar, notebook control for display management and access to
  5. command console.
  6. Classes:
  7. - GMFrame
  8. - GMApp
  9. (C) 2006-2009 by the GRASS Development Team
  10. This program is free software under the GNU General Public
  11. License (>=v2). Read the file COPYING that comes with GRASS
  12. for details.
  13. @author Michael Barton (Arizona State University)
  14. @author Jachym Cepicky (Mendel University of Agriculture)
  15. @author Martin Landa <landa.martin gmail.com>
  16. """
  17. import sys
  18. import os
  19. import time
  20. import traceback
  21. import re
  22. import string
  23. import getopt
  24. import platform
  25. import signal
  26. ### XML
  27. try:
  28. import xml.etree.ElementTree as etree
  29. except ImportError:
  30. import elementtree.ElementTree as etree # Python <= 2.4
  31. ### i18N
  32. import gettext
  33. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode=True)
  34. import gui_modules
  35. gmpath = gui_modules.__path__[0]
  36. sys.path.append(gmpath)
  37. import images
  38. imagepath = images.__path__[0]
  39. sys.path.append(imagepath)
  40. import icons
  41. gmpath = icons.__path__[0]
  42. sys.path.append(gmpath)
  43. import gui_modules.globalvar as globalvar
  44. if not os.getenv("GRASS_WXBUNDLED"):
  45. globalvar.CheckForWx()
  46. import wx
  47. import wx.aui
  48. import wx.combo
  49. import wx.html
  50. import wx.stc
  51. import wx.lib.customtreectrl as CT
  52. import wx.lib.flatnotebook as FN
  53. grassPath = os.path.join(globalvar.ETCDIR, "python")
  54. sys.path.append(grassPath)
  55. from grass.script import core as grass
  56. import gui_modules.utils as utils
  57. import gui_modules.preferences as preferences
  58. import gui_modules.wxgui_utils as wxgui_utils
  59. import gui_modules.mapdisp as mapdisp
  60. import gui_modules.menudata as menudata
  61. import gui_modules.menuform as menuform
  62. import gui_modules.histogram as histogram
  63. import gui_modules.profile as profile
  64. import gui_modules.rules as rules
  65. import gui_modules.mcalc_builder as mapcalculator
  66. import gui_modules.gcmd as gcmd
  67. import gui_modules.georect as georect
  68. import gui_modules.dbm as dbm
  69. import gui_modules.workspace as workspace
  70. import gui_modules.goutput as goutput
  71. import gui_modules.gdialogs as gdialogs
  72. import gui_modules.colorrules as colorrules
  73. import gui_modules.ogc_services as ogc_services
  74. import gui_modules.prompt as prompt
  75. from gui_modules.debug import Debug
  76. from gui_modules.help import MenuTreeWindow
  77. from gui_modules.help import AboutWindow
  78. from icons.icon import Icons
  79. UserSettings = preferences.globalSettings
  80. class GMFrame(wx.Frame):
  81. """
  82. GIS Manager frame with notebook widget for controlling
  83. GRASS GIS. Includes command console page for typing GRASS
  84. (and other) commands, tree widget page for managing GIS map layers.
  85. """
  86. def __init__(self, parent, id=wx.ID_ANY, title=_("GRASS GIS Layer Manager"),
  87. workspace=None):
  88. self.parent = parent
  89. self.baseTitle = title
  90. self.iconsize = (16, 16)
  91. wx.Frame.__init__(self, parent=parent, id=id, size=(550, 450),
  92. style=wx.DEFAULT_FRAME_STYLE)
  93. self.SetTitle(self.baseTitle)
  94. self.SetName("LayerManager")
  95. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  96. self._auimgr = wx.aui.AuiManager(self)
  97. # initialize variables
  98. self.disp_idx = 0 # index value for map displays and layer trees
  99. self.curr_page = '' # currently selected page for layer tree notebook
  100. self.curr_pagenum = '' # currently selected page number for layer tree notebook
  101. self.workspaceFile = workspace # workspace file
  102. self.menucmd = dict() # menuId / cmd
  103. self.georectifying = None # reference to GCP class or None
  104. # list of open dialogs
  105. self.dialogs = dict()
  106. self.dialogs['preferences'] = None
  107. self.dialogs['atm'] = list()
  108. # creating widgets
  109. # -> self.notebook, self.goutput, self.outpage
  110. self.notebook = self.__createNoteBook()
  111. self.menubar, self.menudata = self.__createMenuBar()
  112. self.statusbar = self.CreateStatusBar(number=1)
  113. self.toolbar = self.__createToolBar()
  114. # bindings
  115. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  116. self.Bind(wx.EVT_KEY_UP, self.OnKey)
  117. # minimal frame size
  118. self.SetMinSize((500, 400))
  119. # AUI stuff
  120. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  121. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  122. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  123. self._auimgr.Update()
  124. wx.CallAfter(self.notebook.SetSelection, 0)
  125. wx.CallAfter(self.goutput.cmd_prompt.SetFocus)
  126. # use default window layout ?
  127. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  128. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  129. try:
  130. x, y = map(int, dim.split(',')[0:2])
  131. w, h = map(int, dim.split(',')[2:4])
  132. self.SetPosition((x, y))
  133. self.SetSize((w, h))
  134. except:
  135. pass
  136. self.Show()
  137. # load workspace file if requested
  138. if (self.workspaceFile):
  139. # load given workspace file
  140. if self.LoadWorkspaceFile(self.workspaceFile):
  141. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  142. else:
  143. self.workspaceFile = None
  144. else:
  145. # start default initial display
  146. self.NewDisplay(show=False)
  147. # show map display widnow
  148. # -> OnSize() -> UpdateMap()
  149. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  150. self.curr_page.maptree.mapdisplay.Show()
  151. # redirect stderr to log area
  152. self.goutput.Redirect()
  153. # start with layer manager on top
  154. self.curr_page.maptree.mapdisplay.Raise()
  155. self.Raise()
  156. def __createMenuBar(self):
  157. """!Creates menubar"""
  158. self.menubar = wx.MenuBar()
  159. self.menudata = menudata.Data()
  160. for eachMenuData in self.menudata.GetMenu():
  161. for eachHeading in eachMenuData:
  162. menuLabel = eachHeading[0]
  163. menuItems = eachHeading[1]
  164. self.menubar.Append(self.__createMenu(menuItems), menuLabel)
  165. self.SetMenuBar(self.menubar)
  166. return (self.menubar, self.menudata)
  167. def __createMenu(self, menuData):
  168. """!Creates menu"""
  169. menu = wx.Menu()
  170. for eachItem in menuData:
  171. if len(eachItem) == 2:
  172. label = eachItem[0]
  173. subMenu = self.__createMenu(eachItem[1])
  174. menu.AppendMenu(wx.ID_ANY, label, subMenu)
  175. else:
  176. self.__createMenuItem(menu, *eachItem)
  177. self.Bind(wx.EVT_MENU_HIGHLIGHT_ALL, self.OnMenuHighlight)
  178. return menu
  179. def __createMenuItem(self, menu, label, help, handler, gcmd, keywords, shortcut = '', kind = wx.ITEM_NORMAL):
  180. """!Creates menu items"""
  181. if not label:
  182. menu.AppendSeparator()
  183. return
  184. if len(gcmd) > 0:
  185. helpString = gcmd + ' -- ' + help
  186. else:
  187. helpString = help
  188. if shortcut:
  189. label += '\t' + shortcut
  190. menuItem = menu.Append(wx.ID_ANY, label, helpString, kind)
  191. self.menucmd[menuItem.GetId()] = gcmd
  192. if len(gcmd) > 0 and \
  193. gcmd.split()[0] not in globalvar.grassCmd['all']:
  194. menuItem.Enable (False)
  195. rhandler = eval(handler)
  196. self.Bind(wx.EVT_MENU, rhandler, menuItem)
  197. def __createNoteBook(self):
  198. """!Creates notebook widgets"""
  199. #create main notebook widget
  200. nbStyle = FN.FNB_FANCY_TABS | \
  201. FN.FNB_BOTTOM | \
  202. FN.FNB_NO_NAV_BUTTONS | \
  203. FN.FNB_NO_X_BUTTON
  204. self.notebook = FN.FlatNotebook(parent=self, id=wx.ID_ANY, style=nbStyle)
  205. #self.notebook = wx.aui.AuiNotebook(parent=self, id=wx.ID_ANY, style=wx.aui.AUI_NB_BOTTOM)
  206. #self.notebook.SetFont(wx.Font(pointSize=11, family=wx.FONTFAMILY_DEFAULT, style=wx.NORMAL, weight=0))
  207. # create displays notebook widget and add it to main notebook page
  208. cbStyle = globalvar.FNPageStyle
  209. self.gm_cb = FN.FlatNotebook(self, id=wx.ID_ANY, style=cbStyle)
  210. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  211. self.notebook.AddPage(self.gm_cb, text=_("Map layers for each display"))
  212. # create command output text area and add it to main notebook page
  213. self.goutput = goutput.GMConsole(self, pageid=1)
  214. self.outpage = self.notebook.AddPage(self.goutput, text=_("Command console"))
  215. # bindings
  216. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  217. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  218. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  219. sizer = wx.BoxSizer(wx.VERTICAL)
  220. sizer.Add(item=self.goutput, proportion=1,
  221. flag=wx.EXPAND | wx.ALL, border=1)
  222. self.SetSizer(sizer)
  223. # self.out_sizer.Fit(self.outpage)
  224. self.Layout()
  225. self.Centre()
  226. return self.notebook
  227. def __createToolBar(self):
  228. """!Creates toolbar"""
  229. self.toolbar = self.CreateToolBar()
  230. self.toolbar.SetToolBitmapSize(globalvar.toolbarSize)
  231. for each in self.ToolbarData():
  232. self.AddToolbarButton(self.toolbar, *each)
  233. self.toolbar.Realize()
  234. return self.toolbar
  235. def OnMenuHighlight(self, event):
  236. """
  237. Default menu help handler
  238. """
  239. # Show how to get menu item info from this event handler
  240. id = event.GetMenuId()
  241. item = self.GetMenuBar().FindItemById(id)
  242. if item:
  243. text = item.GetText()
  244. help = item.GetHelp()
  245. # but in this case just call Skip so the default is done
  246. event.Skip()
  247. def OnGeorectify(self, event):
  248. """
  249. Launch georectifier module
  250. """
  251. georect.GeorectWizard(self)
  252. def OnMapsets(self, event):
  253. """
  254. Launch mapset access dialog
  255. """
  256. dlg = preferences.MapsetAccess(parent=self, id=wx.ID_ANY)
  257. dlg.CenterOnScreen()
  258. # if OK is pressed...
  259. if dlg.ShowModal() == wx.ID_OK:
  260. ms = dlg.GetMapsets()
  261. # run g.mapsets with string of accessible mapsets
  262. gcmd.RunCommand('g.mapsets',
  263. parent = self,
  264. mapset = '%s' % ','.join(ms))
  265. def OnRDigit(self, event):
  266. """
  267. Launch raster digitizing module
  268. """
  269. pass
  270. def OnCBPageChanged(self, event):
  271. """!Page in notebook (display) changed"""
  272. old_pgnum = event.GetOldSelection()
  273. new_pgnum = event.GetSelection()
  274. self.curr_page = self.gm_cb.GetCurrentPage()
  275. self.curr_pagenum = self.gm_cb.GetSelection()
  276. try:
  277. self.curr_page.maptree.mapdisplay.SetFocus()
  278. self.curr_page.maptree.mapdisplay.Raise()
  279. except:
  280. pass
  281. event.Skip()
  282. def OnPageChanged(self, event):
  283. """!Page in notebook changed"""
  284. page = event.GetSelection()
  285. if page == self.goutput.pageid:
  286. # remove '(...)'
  287. self.notebook.SetPageText(page, _("Command console"))
  288. event.Skip()
  289. def OnCBPageClosed(self, event):
  290. """
  291. Page of notebook closed
  292. Also close associated map display
  293. """
  294. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  295. maptree = self.curr_page.maptree
  296. if self.workspaceFile:
  297. message = _("Do you want to save changes in the workspace?")
  298. else:
  299. message = _("Do you want to store current settings "
  300. "to workspace file?")
  301. # ask user to save current settings
  302. if maptree.GetCount() > 0:
  303. dlg = wx.MessageDialog(self,
  304. message=message,
  305. caption=_("Close Map Display %d") % (self.curr_pagenum + 1),
  306. style=wx.YES_NO | wx.YES_DEFAULT |
  307. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  308. ret = dlg.ShowModal()
  309. if ret == wx.ID_YES:
  310. if not self.workspaceFile:
  311. self.OnWorkspaceSaveAs()
  312. else:
  313. self.SaveToWorkspaceFile(self.workspaceFile)
  314. elif ret == wx.ID_CANCEL:
  315. event.Veto()
  316. dlg.Destroy()
  317. return
  318. dlg.Destroy()
  319. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  320. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  321. self.curr_page = None
  322. event.Skip()
  323. def GetLogWindow(self):
  324. """!Get widget for command output"""
  325. return self.goutput
  326. def GetMenuCmd(self, event):
  327. """!Get GRASS command from menu item
  328. Return command as a list"""
  329. layer = None
  330. if event:
  331. cmd = self.menucmd[event.GetId()]
  332. try:
  333. cmdlist = cmd.split(' ')
  334. except: # already list?
  335. cmdlist = cmd
  336. # check list of dummy commands for GUI modules that do not have GRASS
  337. # bin modules or scripts.
  338. if cmd in ['vcolors']:
  339. return cmdlist
  340. try:
  341. layer = self.curr_page.maptree.layer_selected
  342. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  343. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  344. except:
  345. layer = None
  346. if layer and len(cmdlist) == 1: # only if no paramaters given
  347. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  348. (type == 'vector' and cmdlist[0][0] == 'v'):
  349. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  350. if input:
  351. cmdlist.append("%s=%s" % (input, name))
  352. return cmdlist
  353. def RunMenuCmd(self, event, cmd = ''):
  354. """!Run command selected from menu"""
  355. if event:
  356. cmd = self.GetMenuCmd(event)
  357. self.goutput.RunCmd(cmd, switchPage=True)
  358. def OnMenuCmd(self, event, cmd = ''):
  359. """!Parse command selected from menu"""
  360. if event:
  361. cmd = self.GetMenuCmd(event)
  362. menuform.GUI().ParseCommand(cmd, parentframe=self)
  363. def OnRunScript(self, event):
  364. """!Run script"""
  365. # open dialog and choose script file
  366. dlg = wx.FileDialog(parent = self, message = _("Choose script file"),
  367. defaultDir = os.getcwd(), wildcard = _("Bash script (*.sh)|*.sh|Python script (*.py)|*.py"))
  368. filename = None
  369. if dlg.ShowModal() == wx.ID_OK:
  370. filename = dlg.GetPath()
  371. if not filename:
  372. return False
  373. if not os.path.exists(filename):
  374. wx.MessageBox(parent = self,
  375. message = _("Script file '%s' doesn't exist. Operation cancelled.") % filename,
  376. caption = _("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  377. return
  378. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  379. self.goutput.RunCmd(filename, switchPage = True)
  380. def OnChangeLocation(self, event):
  381. """Change current location"""
  382. dlg = gdialogs.LocationDialog(parent = self)
  383. if dlg.ShowModal() == wx.ID_OK:
  384. location, mapset = dlg.GetValues()
  385. if location and mapset:
  386. ret = gcmd.RunCommand("g.gisenv",
  387. set = "LOCATION_NAME=%s" % location)
  388. ret += gcmd.RunCommand("g.gisenv",
  389. set = "MAPSET=%s" % mapset)
  390. if ret > 0:
  391. wx.MessageBox(parent = self,
  392. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  393. { 'loc' : location, 'mapset' : mapset },
  394. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  395. else:
  396. # close workspace
  397. self.OnWorkspaceClose()
  398. self.OnWorkspaceNew()
  399. wx.MessageBox(parent = self,
  400. message = _("Current location is <%(loc)s>.\n"
  401. "Current mapset is <%(mapset)s>.") % \
  402. { 'loc' : location, 'mapset' : mapset },
  403. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  404. def OnChangeMapset(self, event):
  405. """Change current mapset"""
  406. dlg = gdialogs.MapsetDialog(parent = self)
  407. if dlg.ShowModal() == wx.ID_OK:
  408. mapset = dlg.GetMapset()
  409. if mapset:
  410. if gcmd.RunCommand("g.gisenv",
  411. set = "MAPSET=%s" % mapset) != 0:
  412. wx.MessageBox(parent = self,
  413. message = _("Unable to switch to mapset <%s>.") % mapset,
  414. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  415. else:
  416. wx.MessageBox(parent = self,
  417. message = _("Current mapset is <%s>.") % mapset,
  418. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  419. def OnNewVector(self, event):
  420. """!Create new vector map layer"""
  421. name, add = gdialogs.CreateNewVector(self, log = self.goutput,
  422. cmd = (('v.edit',
  423. { 'tool' : 'create' },
  424. 'map')))
  425. if name and add:
  426. # add layer to map layer tree
  427. self.curr_page.maptree.AddLayer(ltype='vector',
  428. lname=name,
  429. lchecked=True,
  430. lopacity=1.0,
  431. lcmd=['d.vect', 'map=%s' % name])
  432. def OnMenuTree(self, event):
  433. """!Show dialog with menu tree"""
  434. dlg = MenuTreeWindow(self)
  435. dlg.CentreOnScreen()
  436. dlg.Show()
  437. def OnAboutGRASS(self, event):
  438. """!Display 'About GRASS' dialog"""
  439. win = AboutWindow(self)
  440. win.CentreOnScreen()
  441. win.Show(True)
  442. def OnWorkspace(self, event):
  443. """!Workspace menu (new, load)"""
  444. point = wx.GetMousePosition()
  445. menu = wx.Menu()
  446. # Add items to the menu
  447. new = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceNew"].GetLabel())
  448. new.SetBitmap(Icons["workspaceNew"].GetBitmap(self.iconsize))
  449. menu.AppendItem(new)
  450. self.Bind(wx.EVT_MENU, self.OnWorkspaceNew, new)
  451. load = wx.MenuItem(menu, wx.ID_ANY, Icons["workspaceLoad"].GetLabel())
  452. load.SetBitmap(Icons["workspaceLoad"].GetBitmap(self.iconsize))
  453. menu.AppendItem(load)
  454. self.Bind(wx.EVT_MENU, self.OnWorkspaceLoad, load)
  455. # create menu
  456. self.PopupMenu(menu)
  457. menu.Destroy()
  458. def OnWorkspaceNew(self, event=None):
  459. """!Create new workspace file
  460. Erase current workspace settings first"""
  461. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  462. # start new map display if no display is available
  463. if not self.curr_page:
  464. self.NewDisplay()
  465. maptree = self.curr_page.maptree
  466. # ask user to save current settings
  467. if maptree.GetCount() > 0:
  468. dlg = wx.MessageDialog(self, message=_("Current workspace is not empty. "
  469. "Do you want to store current settings "
  470. "to workspace file?"),
  471. caption=_("Create new workspace?"),
  472. style=wx.YES_NO | wx.YES_DEFAULT | \
  473. wx.CANCEL | wx.ICON_QUESTION)
  474. ret = dlg.ShowModal()
  475. if ret == wx.ID_YES:
  476. self.OnWorkspaceSaveAs()
  477. elif ret == wx.ID_CANCEL:
  478. dlg.Destroy()
  479. return
  480. dlg.Destroy()
  481. # delete all items
  482. maptree.DeleteAllItems()
  483. # add new root element
  484. maptree.root = maptree.AddRoot("Map Layers")
  485. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  486. # no workspace file loaded
  487. self.workspaceFile = None
  488. self.SetTitle(self.baseTitle)
  489. def OnWorkspaceOpen(self, event=None):
  490. """!Open file with workspace definition"""
  491. dlg = wx.FileDialog(parent=self, message=_("Choose workspace file"),
  492. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"))
  493. filename = ''
  494. if dlg.ShowModal() == wx.ID_OK:
  495. filename = dlg.GetPath()
  496. if filename == '':
  497. return
  498. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  499. # delete current layer tree content
  500. self.OnWorkspaceClose()
  501. self.LoadWorkspaceFile(filename)
  502. self.workspaceFile = filename
  503. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  504. def LoadWorkspaceFile(self, filename):
  505. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  506. @todo Validate against DTD
  507. @return True on success
  508. @return False on error
  509. """
  510. # dtd
  511. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  512. # parse workspace file
  513. try:
  514. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  515. except Exception, err:
  516. raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
  517. "Invalid file, unable to parse XML document."
  518. "\n\n%(err)s") % { 'file' : filename, 'err': err},
  519. parent = self)
  520. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  521. parent=self)
  522. wx.Yield()
  523. #
  524. # load layer manager window properties
  525. #
  526. if UserSettings.Get(group='workspace', key='posManager', subkey='enabled') is False:
  527. if gxwXml.layerManager['pos']:
  528. self.SetPosition(gxwXml.layerManager['pos'])
  529. if gxwXml.layerManager['size']:
  530. self.SetSize(gxwXml.layerManager['size'])
  531. #
  532. # start map displays first (list of layers can be empty)
  533. #
  534. displayId = 0
  535. mapdisplay = []
  536. for display in gxwXml.displays:
  537. mapdisplay.append(self.NewDisplay(show=False))
  538. maptree = self.gm_cb.GetPage(displayId).maptree
  539. # set windows properties
  540. mapdisplay[-1].SetProperties(render=display['render'],
  541. mode=display['mode'],
  542. showCompExtent=display['showCompExtent'],
  543. constrainRes=display['constrainRes'],
  544. projection=display['projection']['enabled'])
  545. if display['projection']['enabled']:
  546. if display['projection']['epsg']:
  547. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  548. value = display['projection']['epsg'])
  549. if display['projection']['proj']:
  550. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  551. value = display['projection']['proj'])
  552. # set position and size of map display
  553. if UserSettings.Get(group='workspace', key='posDisplay', subkey='enabled') is False:
  554. if display['pos']:
  555. mapdisplay[-1].SetPosition(display['pos'])
  556. if display['size']:
  557. mapdisplay[-1].SetSize(display['size'])
  558. # set extent if defined
  559. if display['extent']:
  560. w, s, e, n = display['extent']
  561. maptree.Map.region = maptree.Map.GetRegion(w=w, s=s, e=e, n=n)
  562. mapdisplay[-1].Show()
  563. displayId += 1
  564. maptree = None
  565. selected = [] # list of selected layers
  566. #
  567. # load list of map layers
  568. #
  569. for layer in gxwXml.layers:
  570. display = layer['display']
  571. maptree = self.gm_cb.GetPage(display).maptree
  572. newItem = maptree.AddLayer(ltype=layer['type'],
  573. lname=layer['name'],
  574. lchecked=layer['checked'],
  575. lopacity=layer['opacity'],
  576. lcmd=layer['cmd'],
  577. lgroup=layer['group'],
  578. lnviz=layer['nviz'],
  579. lvdigit=layer['vdigit'])
  580. if layer.has_key('selected'):
  581. if layer['selected']:
  582. selected.append((maptree, newItem))
  583. else:
  584. maptree.SelectItem(newItem, select=False)
  585. for maptree, layer in selected:
  586. if not maptree.IsSelected(layer):
  587. maptree.SelectItem(layer, select=True)
  588. maptree.layer_selected = layer
  589. busy.Destroy()
  590. if maptree:
  591. # reverse list of map layers
  592. maptree.Map.ReverseListOfLayers()
  593. for mdisp in mapdisplay:
  594. mdisp.MapWindow2D.UpdateMap()
  595. return True
  596. def OnWorkspaceLoad(self, event=None):
  597. """!Load given map layers into layer tree"""
  598. dialog = gdialogs.LoadMapLayersDialog(parent=self, title=_("Load map layers into layer tree"))
  599. if dialog.ShowModal() == wx.ID_OK:
  600. # start new map display if no display is available
  601. if not self.curr_page:
  602. self.NewDisplay()
  603. maptree = self.curr_page.maptree
  604. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  605. parent=self)
  606. wx.Yield()
  607. for layerName in dialog.GetMapLayers():
  608. if dialog.GetLayerType() == 'raster':
  609. cmd = ['d.rast', 'map=%s' % layerName]
  610. elif dialog.GetLayerType() == 'vector':
  611. cmd = ['d.vect', 'map=%s' % layerName]
  612. newItem = maptree.AddLayer(ltype=dialog.GetLayerType(),
  613. lname=layerName,
  614. lchecked=True,
  615. lopacity=1.0,
  616. lcmd=cmd,
  617. lgroup=None)
  618. busy.Destroy()
  619. def OnWorkspaceLoadGrcFile(self, event):
  620. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  621. dlg = wx.FileDialog(parent=self, message=_("Choose GRC file to load"),
  622. defaultDir=os.getcwd(), wildcard=_("Old GRASS Workspace File (*.grc)|*.grc"))
  623. filename = ''
  624. if dlg.ShowModal() == wx.ID_OK:
  625. filename = dlg.GetPath()
  626. if filename == '':
  627. return
  628. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  629. # start new map display if no display is available
  630. if not self.curr_page:
  631. self.NewDisplay()
  632. busy = wx.BusyInfo(message=_("Please wait, loading workspace..."),
  633. parent=self)
  634. wx.Yield()
  635. maptree = None
  636. for layer in workspace.ProcessGrcFile(filename).read(self):
  637. maptree = self.gm_cb.GetPage(layer['display']).maptree
  638. newItem = maptree.AddLayer(ltype=layer['type'],
  639. lname=layer['name'],
  640. lchecked=layer['checked'],
  641. lopacity=layer['opacity'],
  642. lcmd=layer['cmd'],
  643. lgroup=layer['group'])
  644. busy.Destroy()
  645. if maptree:
  646. # reverse list of map layers
  647. maptree.Map.ReverseListOfLayers()
  648. def OnWorkspaceSaveAs(self, event=None):
  649. """!Save workspace definition to selected file"""
  650. dlg = wx.FileDialog(parent=self, message=_("Choose file to save current workspace"),
  651. defaultDir=os.getcwd(), wildcard=_("GRASS Workspace File (*.gxw)|*.gxw"), style=wx.FD_SAVE)
  652. filename = ''
  653. if dlg.ShowModal() == wx.ID_OK:
  654. filename = dlg.GetPath()
  655. if filename == '':
  656. return False
  657. # check for extension
  658. if filename[-4:] != ".gxw":
  659. filename += ".gxw"
  660. if os.path.exists(filename):
  661. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  662. "Do you want to overwrite this file?") % filename,
  663. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  664. if dlg.ShowModal() != wx.ID_YES:
  665. dlg.Destroy()
  666. return False
  667. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  668. self.SaveToWorkspaceFile(filename)
  669. self.workspaceFile = filename
  670. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  671. def OnWorkspaceSave(self, event=None):
  672. """!Save file with workspace definition"""
  673. if self.workspaceFile:
  674. dlg = wx.MessageDialog(self, message=_("Workspace file <%s> already exists. "
  675. "Do you want to overwrite this file?") % \
  676. self.workspaceFile,
  677. caption=_("Save workspace"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  678. if dlg.ShowModal() == wx.ID_NO:
  679. dlg.Destroy()
  680. else:
  681. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  682. self.SaveToWorkspaceFile(self.workspaceFile)
  683. else:
  684. self.OnWorkspaceSaveAs()
  685. def SaveToWorkspaceFile(self, filename):
  686. """!Save layer tree layout to workspace file
  687. Return True on success, False on error
  688. """
  689. try:
  690. file = open(filename, "w")
  691. except IOError:
  692. wx.MessageBox(parent=self,
  693. message=_("Unable to open workspace file <%s> for writing.") % filename,
  694. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  695. return False
  696. try:
  697. workspace.WriteWorkspaceFile(lmgr=self, file=file)
  698. except StandardError, e:
  699. file.close()
  700. wx.MessageBox(parent=self,
  701. message=_("Writing current settings to workspace file failed (%s)." % e),
  702. caption=_("Error"),
  703. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  704. return False
  705. file.close()
  706. return True
  707. def OnWorkspaceClose(self, event=None):
  708. """!Close file with workspace definition
  709. If workspace has been modified ask user to save the changes.
  710. """
  711. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  712. self.workspaceFile = None
  713. self.SetTitle(self.baseTitle)
  714. displays = []
  715. for page in range(0, self.gm_cb.GetPageCount()):
  716. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  717. for display in displays:
  718. display.OnCloseWindow(event)
  719. self.disp_idx = 0
  720. self.curr_page = None
  721. def RulesCmd(self, event, cmd = ''):
  722. """
  723. Launches dialog for commands that need rules
  724. input and processes rules
  725. """
  726. if event:
  727. cmd = self.GetMenuCmd(event)
  728. if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
  729. ctable = colorrules.ColorTable(self, cmd=cmd[0])
  730. ctable.Show()
  731. else:
  732. dlg = rules.RulesText(self, cmd=cmd)
  733. dlg.CenterOnScreen()
  734. if dlg.ShowModal() == wx.ID_OK:
  735. gtemp = utils.GetTempfile()
  736. output = open(gtemp, "w")
  737. try:
  738. output.write(dlg.rules)
  739. finally:
  740. output.close()
  741. cmdlist = [cmd[0],
  742. 'input=%s' % dlg.inmap,
  743. 'output=%s' % dlg.outmap,
  744. 'rules=%s' % gtemp]
  745. if dlg.overwrite == True:
  746. cmdlist.append('--o')
  747. dlg.Destroy()
  748. self.goutput.RunCmd(cmdlist)
  749. def OnPreferences(self, event):
  750. """!General GUI preferences/settings"""
  751. if not self.dialogs['preferences']:
  752. dlg = preferences.PreferencesDialog(parent=self)
  753. self.dialogs['preferences'] = dlg
  754. self.dialogs['preferences'].CenterOnScreen()
  755. self.dialogs['preferences'].ShowModal()
  756. def DispHistogram(self, event):
  757. """
  758. Init histogram display canvas and tools
  759. """
  760. self.histogram = histogram.HistFrame(self,
  761. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  762. style=wx.DEFAULT_FRAME_STYLE)
  763. #show new display
  764. self.histogram.Show()
  765. self.histogram.Refresh()
  766. self.histogram.Update()
  767. def DispProfile(self, event):
  768. """
  769. Init profile canvas and tools
  770. """
  771. self.profile = profile.ProfileFrame(self,
  772. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  773. style=wx.DEFAULT_FRAME_STYLE)
  774. self.profile.Show()
  775. self.profile.Refresh()
  776. self.profile.Update()
  777. def DispMapCalculator(self, event):
  778. """
  779. Init map calculator for interactive creation of mapcalc statements
  780. """
  781. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  782. dimension=2)
  783. def Disp3DMapCalculator(self, event):
  784. """
  785. Init map calculator for interactive creation of mapcalc statements
  786. """
  787. self.mapcalculator = mapcalculator.MapCalcFrame(self, wx.ID_ANY, title='',
  788. dimension=3)
  789. def AddToolbarButton(self, toolbar, label, icon, help, handler):
  790. """!Adds button to the given toolbar"""
  791. if not label:
  792. toolbar.AddSeparator()
  793. return
  794. tool = toolbar.AddLabelTool(id=wx.ID_ANY, label=label, bitmap=icon, shortHelp=help)
  795. self.Bind(wx.EVT_TOOL, handler, tool)
  796. def ToolbarData(self):
  797. return (
  798. ('newdisplay', Icons["newdisplay"].GetBitmap(),
  799. Icons["newdisplay"].GetLabel(), self.OnNewDisplay),
  800. ('', '', '', ''),
  801. ('workspaceLoad', Icons["workspaceLoad"].GetBitmap(),
  802. Icons["workspaceLoad"].GetLabel(), self.OnWorkspace),
  803. ('workspaceOpen', Icons["workspaceOpen"].GetBitmap(),
  804. Icons["workspaceOpen"].GetLabel(), self.OnWorkspaceOpen),
  805. ('workspaceSave', Icons["workspaceSave"].GetBitmap(),
  806. Icons["workspaceSave"].GetLabel(), self.OnWorkspaceSave),
  807. ('', '', '', ''),
  808. ('addrast', Icons["addrast"].GetBitmap(),
  809. Icons["addrast"].GetLabel(), self.OnAddRaster),
  810. ('addshaded', Icons["addshaded"].GetBitmap(),
  811. _("Add various raster-based map layers"), self.OnAddRasterMisc),
  812. ('addvect', Icons["addvect"].GetBitmap(),
  813. Icons["addvect"].GetLabel(), self.OnAddVector),
  814. ('addthematic', Icons["addthematic"].GetBitmap(),
  815. _("Add various vector-based map layer"), self.OnAddVectorMisc),
  816. ('addcmd', Icons["addcmd"].GetBitmap(),
  817. Icons["addcmd"].GetLabel(), self.OnAddCommand),
  818. ('addgrp', Icons["addgrp"].GetBitmap(),
  819. Icons["addgrp"].GetLabel(), self.OnAddGroup),
  820. ('addovl', Icons["addovl"].GetBitmap(),
  821. Icons["addovl"].GetLabel(), self.OnAddOverlay),
  822. ('delcmd', Icons["delcmd"].GetBitmap(),
  823. Icons["delcmd"].GetLabel(), self.OnDeleteLayer),
  824. ('', '', '', ''),
  825. ('attrtable', Icons["attrtable"].GetBitmap(),
  826. Icons["attrtable"].GetLabel(), self.OnShowAttributeTable)
  827. )
  828. def OnImportDxfFile(self, event):
  829. """!Convert multiple DXF layers to GRASS vector map layers"""
  830. dlg = gdialogs.MultiImportDialog(parent=self, type='dxf',
  831. title=_("Import DXF layers"))
  832. dlg.ShowModal()
  833. def OnImportGdalLayers(self, event):
  834. """!Convert multiple GDAL layers to GRASS raster map layers"""
  835. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  836. title=_("Import GDAL layers"))
  837. dlg.ShowModal()
  838. def OnLinkGdalLayers(self, event):
  839. """!Link multiple GDAL layers to GRASS raster map layers"""
  840. dlg = gdialogs.MultiImportDialog(parent=self, type='gdal',
  841. title=_("Link GDAL layers"),
  842. link = True)
  843. dlg.ShowModal()
  844. def OnImportOgrLayers(self, event):
  845. """!Convert multiple OGR layers to GRASS vector map layers"""
  846. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  847. title=_("Import OGR layers"))
  848. dlg.ShowModal()
  849. def OnLinkOgrLayers(self, event):
  850. """!Links multiple OGR layers to GRASS vector map layers"""
  851. dlg = gdialogs.MultiImportDialog(parent=self, type='ogr',
  852. title=_("Link OGR layers"),
  853. link = True)
  854. dlg.ShowModal()
  855. def OnImportWMS(self, event):
  856. """!Import data from OGC WMS server"""
  857. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  858. dlg.CenterOnScreen()
  859. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  860. layers = dlg.GetLayers()
  861. if len(layers.keys()) > 0:
  862. for layer in layers.keys():
  863. cmd = ['r.in.wms',
  864. 'mapserver=%s' % dlg.GetSettings()['server'],
  865. 'layers=%s' % layer,
  866. 'output=%s' % layer]
  867. styles = ','.join(layers[layer])
  868. if styles:
  869. cmd.append('styles=%s' % styles)
  870. self.goutput.RunCmd(cmd, switchPage = True)
  871. else:
  872. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  873. dlg.Destroy()
  874. def OnShowAttributeTable(self, event):
  875. """
  876. Show attribute table of the given vector map layer
  877. """
  878. if not self.curr_page:
  879. self.MsgNoLayerSelected()
  880. return
  881. layer = self.curr_page.maptree.layer_selected
  882. # no map layer selected
  883. if not layer:
  884. self.MsgNoLayerSelected()
  885. return
  886. # available only for vector map layers
  887. try:
  888. maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
  889. except:
  890. maptype = None
  891. if not maptype or maptype != 'vector':
  892. wx.MessageBox(parent=self,
  893. message=_("Attribute management is available only "
  894. "for vector maps."),
  895. caption=_("Message"),
  896. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  897. return
  898. if not self.curr_page.maptree.GetPyData(layer)[0]:
  899. return
  900. dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
  901. if not dcmd:
  902. return
  903. busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
  904. parent=self)
  905. wx.Yield()
  906. dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
  907. size=wx.Size(500, 300),
  908. item=layer, log=self.goutput)
  909. busy.Destroy()
  910. # register ATM dialog
  911. self.dialogs['atm'].append(dbmanager)
  912. # show ATM window
  913. dbmanager.Show()
  914. def OnNewDisplay(self, event=None):
  915. """!Create new layer tree and map display instance"""
  916. self.NewDisplay()
  917. def NewDisplay(self, show=True):
  918. """!Create new layer tree, which will
  919. create an associated map display frame
  920. @param show show map display window if True
  921. @return reference to mapdisplay intance
  922. """
  923. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  924. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  925. self.pg_panel = wx.Panel(self.gm_cb, id=wx.ID_ANY, style= wx.EXPAND)
  926. self.gm_cb.AddPage(self.pg_panel, text="Display "+ str(self.disp_idx + 1), select = True)
  927. self.curr_page = self.gm_cb.GetCurrentPage()
  928. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  929. self.curr_page.maptree = wxgui_utils.LayerTree(self.curr_page, id=wx.ID_ANY, pos=wx.DefaultPosition,
  930. size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS
  931. |wx.TR_LINES_AT_ROOT|wx.TR_HIDE_ROOT
  932. |wx.TR_DEFAULT_STYLE|wx.NO_BORDER|wx.FULL_REPAINT_ON_RESIZE,
  933. idx=self.disp_idx, lmgr=self, notebook=self.gm_cb,
  934. auimgr=self._auimgr, showMapDisplay=show)
  935. # layout for controls
  936. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  937. cb_boxsizer.Add(self.curr_page.maptree, proportion=1, flag=wx.EXPAND, border=1)
  938. self.curr_page.SetSizer(cb_boxsizer)
  939. cb_boxsizer.Fit(self.curr_page.maptree)
  940. self.curr_page.Layout()
  941. self.curr_page.maptree.Layout()
  942. # use default window layout
  943. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  944. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  945. idx = 4 + self.disp_idx * 4
  946. try:
  947. x, y = map(int, dim.split(',')[idx:idx + 2])
  948. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  949. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  950. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  951. except:
  952. pass
  953. self.disp_idx += 1
  954. return self.curr_page.maptree.mapdisplay
  955. # toolBar button handlers
  956. def OnAddRaster(self, event):
  957. """!Add raster map layer"""
  958. # start new map display if no display is available
  959. if not self.curr_page:
  960. self.NewDisplay(show=False)
  961. self.AddRaster(event)
  962. def OnAddRasterMisc(self, event):
  963. """!Add raster menu"""
  964. # start new map display if no display is available
  965. if not self.curr_page:
  966. self.NewDisplay(show=False)
  967. point = wx.GetMousePosition()
  968. rastmenu = wx.Menu()
  969. # add items to the menu
  970. if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
  971. addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
  972. addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
  973. rastmenu.AppendItem(addrast3d)
  974. self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
  975. addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
  976. addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
  977. rastmenu.AppendItem(addshaded)
  978. self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
  979. addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
  980. addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
  981. rastmenu.AppendItem(addrgb)
  982. self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
  983. addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
  984. addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
  985. rastmenu.AppendItem(addhis)
  986. self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
  987. addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
  988. addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
  989. rastmenu.AppendItem(addrastarrow)
  990. self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
  991. addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
  992. addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
  993. rastmenu.AppendItem(addrastnums)
  994. self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
  995. # Popup the menu. If an item is selected then its handler
  996. # will be called before PopupMenu returns.
  997. self.PopupMenu(rastmenu)
  998. rastmenu.Destroy()
  999. # show map display
  1000. self.curr_page.maptree.mapdisplay.Show()
  1001. def OnAddVector(self, event):
  1002. """!Add vector map layer"""
  1003. # start new map display if no display is available
  1004. if not self.curr_page:
  1005. self.NewDisplay(show=False)
  1006. self.AddVector(event)
  1007. def OnAddVectorMisc(self, event):
  1008. """!Add vector menu"""
  1009. # start new map display if no display is available
  1010. if not self.curr_page:
  1011. self.NewDisplay(show=False)
  1012. point = wx.GetMousePosition()
  1013. vectmenu = wx.Menu()
  1014. addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
  1015. addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
  1016. vectmenu.AppendItem(addtheme)
  1017. self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
  1018. addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
  1019. addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
  1020. vectmenu.AppendItem(addchart)
  1021. self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
  1022. # Popup the menu. If an item is selected then its handler
  1023. # will be called before PopupMenu returns.
  1024. self.PopupMenu(vectmenu)
  1025. vectmenu.Destroy()
  1026. # show map display
  1027. self.curr_page.maptree.mapdisplay.Show()
  1028. def OnAddOverlay(self, event):
  1029. """!Add decoration overlay menu"""
  1030. # start new map display if no display is available
  1031. if not self.curr_page:
  1032. self.NewDisplay(show=False)
  1033. point = wx.GetMousePosition()
  1034. ovlmenu = wx.Menu()
  1035. addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
  1036. addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
  1037. ovlmenu.AppendItem(addgrid)
  1038. self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
  1039. addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
  1040. addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
  1041. ovlmenu.AppendItem(addlabels)
  1042. self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
  1043. addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
  1044. addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
  1045. ovlmenu.AppendItem(addgeodesic)
  1046. self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
  1047. addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
  1048. addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
  1049. ovlmenu.AppendItem(addrhumb)
  1050. self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
  1051. # Popup the menu. If an item is selected then its handler
  1052. # will be called before PopupMenu returns.
  1053. self.PopupMenu(ovlmenu)
  1054. ovlmenu.Destroy()
  1055. # show map display
  1056. self.curr_page.maptree.mapdisplay.Show()
  1057. def AddRaster(self, event):
  1058. self.notebook.SetSelection(0)
  1059. self.curr_page.maptree.AddLayer('raster')
  1060. def AddRaster3d(self, event):
  1061. self.notebook.SetSelection(0)
  1062. self.curr_page.maptree.AddLayer('3d-raster')
  1063. def AddRGB(self, event):
  1064. """!Add RGB layer"""
  1065. self.notebook.SetSelection(0)
  1066. self.curr_page.maptree.AddLayer('rgb')
  1067. def AddHIS(self, event):
  1068. """!Add HIS layer"""
  1069. self.notebook.SetSelection(0)
  1070. self.curr_page.maptree.AddLayer('his')
  1071. def AddShaded(self, event):
  1072. """!Add shaded relief map layer"""
  1073. self.notebook.SetSelection(0)
  1074. self.curr_page.maptree.AddLayer('shaded')
  1075. def AddRastarrow(self, event):
  1076. """!Add raster flow arrows map"""
  1077. self.notebook.SetSelection(0)
  1078. self.curr_page.maptree.AddLayer('rastarrow')
  1079. def AddRastnum(self, event):
  1080. """!Add raster map with cell numbers"""
  1081. self.notebook.SetSelection(0)
  1082. self.curr_page.maptree.AddLayer('rastnum')
  1083. def AddVector(self, event):
  1084. """!Add vector layer"""
  1085. self.notebook.SetSelection(0)
  1086. self.curr_page.maptree.AddLayer('vector')
  1087. def AddThemeMap(self, event):
  1088. """!Add thematic map layer"""
  1089. self.notebook.SetSelection(0)
  1090. self.curr_page.maptree.AddLayer('thememap')
  1091. def AddThemeChart(self, event):
  1092. """!Add thematic chart layer"""
  1093. self.notebook.SetSelection(0)
  1094. self.curr_page.maptree.AddLayer('themechart')
  1095. def OnAddCommand(self, event):
  1096. """!Add command line layer"""
  1097. # start new map display if no display is available
  1098. if not self.curr_page:
  1099. self.NewDisplay(show=False)
  1100. self.notebook.SetSelection(0)
  1101. self.curr_page.maptree.AddLayer('command')
  1102. # show map display
  1103. self.curr_page.maptree.mapdisplay.Show()
  1104. def OnAddGroup(self, event):
  1105. """!Add layer group"""
  1106. # start new map display if no display is available
  1107. if not self.curr_page:
  1108. self.NewDisplay(show=False)
  1109. self.notebook.SetSelection(0)
  1110. self.curr_page.maptree.AddLayer('group')
  1111. # show map display
  1112. self.curr_page.maptree.mapdisplay.Show()
  1113. def AddGrid(self, event):
  1114. """!Add layer grid"""
  1115. self.notebook.SetSelection(0)
  1116. self.curr_page.maptree.AddLayer('grid')
  1117. def AddGeodesic(self, event):
  1118. """!Add layer geodesic"""
  1119. self.notebook.SetSelection(0)
  1120. self.curr_page.maptree.AddLayer('geodesic')
  1121. def AddRhumb(self, event):
  1122. """!Add layer rhumb"""
  1123. self.notebook.SetSelection(0)
  1124. self.curr_page.maptree.AddLayer('rhumb')
  1125. def OnAddLabels(self, event):
  1126. """!Add layer vector labels"""
  1127. # start new map display if no display is available
  1128. if not self.curr_page:
  1129. self.NewDisplay(show=False)
  1130. self.notebook.SetSelection(0)
  1131. self.curr_page.maptree.AddLayer('labels')
  1132. # show map display
  1133. self.curr_page.maptree.mapdisplay.Show()
  1134. def OnDeleteLayer(self, event):
  1135. """
  1136. Delete selected map display layer in GIS Manager tree widget
  1137. """
  1138. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1139. self.MsgNoLayerSelected()
  1140. return
  1141. if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
  1142. layerName = ''
  1143. for item in self.curr_page.maptree.GetSelections():
  1144. name = str(self.curr_page.maptree.GetItemText(item))
  1145. idx = name.find('(opacity')
  1146. if idx > -1:
  1147. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1148. else:
  1149. layerName += '<' + name + '>,\n'
  1150. layerName = layerName.rstrip(',\n')
  1151. if len(layerName) > 2: # <>
  1152. message = _("Do you want to remove map layer(s)\n%s\n"
  1153. "from layer tree?") % layerName
  1154. else:
  1155. message = _("Do you want to remove selected map layer(s) "
  1156. "from layer tree?")
  1157. dlg = wx.MessageDialog (parent=self, message=message,
  1158. caption=_("Remove map layer"),
  1159. style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
  1160. if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
  1161. dlg.Destroy()
  1162. return
  1163. dlg.Destroy()
  1164. for layer in self.curr_page.maptree.GetSelections():
  1165. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1166. self.curr_page.maptree.DeleteChildren(layer)
  1167. self.curr_page.maptree.Delete(layer)
  1168. def OnKey(self, event):
  1169. """!Check hotkey"""
  1170. kc = event.GetKeyCode()
  1171. if event.ControlDown():
  1172. if kc == wx.WXK_TAB:
  1173. # switch layer list / command output
  1174. if self.notebook.GetSelection() == 0:
  1175. self.notebook.SetSelection(1)
  1176. else:
  1177. self.notebook.SetSelection(0)
  1178. try:
  1179. ckc = chr(kc)
  1180. except ValueError:
  1181. event.Skip()
  1182. return
  1183. if event.AltDown():
  1184. if kc == 'R':
  1185. self.OnAddRaster(None)
  1186. elif kc == 'V':
  1187. self.OnAddVector(None)
  1188. event.Skip()
  1189. def OnQuit(self, event):
  1190. """!Quit GRASS session (wxGUI and shell)"""
  1191. # quit wxGUI session
  1192. self.OnCloseWindow(event)
  1193. # quit GRASS shell
  1194. try:
  1195. pid = int(os.environ['GIS_LOCK'])
  1196. except (KeyError, ValueError):
  1197. sys.stderr.write('\n')
  1198. sys.stderr.write(_("WARNING: Unable to quit GRASS, uknown GIS_LOCK"))
  1199. return
  1200. os.kill(pid, signal.SIGQUIT)
  1201. def OnCloseWindow(self, event):
  1202. """!Cleanup when wxGUI is quit"""
  1203. if not self.curr_page:
  1204. self._auimgr.UnInit()
  1205. self.Destroy()
  1206. return
  1207. maptree = self.curr_page.maptree
  1208. if UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  1209. if self.workspaceFile:
  1210. message = _("Do you want to save changes in the workspace?")
  1211. else:
  1212. message = _("Do you want to store current settings "
  1213. "to workspace file?")
  1214. # ask user to save current settings
  1215. if maptree.GetCount() > 0:
  1216. dlg = wx.MessageDialog(self,
  1217. message=message,
  1218. caption=_("Quit GRASS GUI"),
  1219. style=wx.YES_NO | wx.YES_DEFAULT |
  1220. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1221. ret = dlg.ShowModal()
  1222. if ret == wx.ID_YES:
  1223. if not self.workspaceFile:
  1224. self.OnWorkspaceSaveAs()
  1225. else:
  1226. self.SaveToWorkspaceFile(self.workspaceFile)
  1227. elif ret == wx.ID_CANCEL:
  1228. event.Veto()
  1229. dlg.Destroy()
  1230. return
  1231. dlg.Destroy()
  1232. # don't ask any more...
  1233. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1234. value = False)
  1235. for page in range(self.gm_cb.GetPageCount()):
  1236. self.gm_cb.GetPage(0).maptree.mapdisplay.OnCloseWindow(event)
  1237. self.gm_cb.DeleteAllPages()
  1238. self._auimgr.UnInit()
  1239. self.Destroy()
  1240. def MsgNoLayerSelected(self):
  1241. """!Show dialog message 'No layer selected'"""
  1242. wx.MessageBox(parent=self,
  1243. message=_("No map layer selected. Operation cancelled."),
  1244. caption=_("Message"),
  1245. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1246. class GMApp(wx.App):
  1247. def __init__(self, workspace = None):
  1248. """!Main GUI class.
  1249. @param workspace path to the workspace file
  1250. """
  1251. self.workspaceFile = workspace
  1252. # call parent class initializer
  1253. wx.App.__init__(self, False)
  1254. def OnInit(self):
  1255. """!Initialize all available image handlers
  1256. @return True
  1257. """
  1258. wx.InitAllImageHandlers()
  1259. # create splash screen
  1260. introImagePath = os.path.join(globalvar.ETCWXDIR, "images", "intro.png")
  1261. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1262. introBmp = introImage.ConvertToBitmap()
  1263. wx.SplashScreen (bitmap=introBmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1264. milliseconds=1500, parent=None, id=wx.ID_ANY)
  1265. wx.Yield()
  1266. # create and show main frame
  1267. mainframe = GMFrame(parent=None, id=wx.ID_ANY,
  1268. workspace = self.workspaceFile)
  1269. mainframe.Show()
  1270. self.SetTopWindow(mainframe)
  1271. return True
  1272. class Usage(Exception):
  1273. def __init__(self, msg):
  1274. self.msg = msg
  1275. def printHelp():
  1276. """!Print program help"""
  1277. print >> sys.stderr, "Usage:"
  1278. print >> sys.stderr, " python wxgui.py [options]"
  1279. print >> sys.stderr, "%sOptions:" % os.linesep
  1280. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1281. sys.exit(0)
  1282. def process_opt(opts, args):
  1283. """!Process command-line arguments"""
  1284. workspaceFile = None
  1285. for o, a in opts:
  1286. if o in ("-h", "--help"):
  1287. printHelp()
  1288. if o in ("-w", "--workspace"):
  1289. if a != '':
  1290. workspaceFile = str(a)
  1291. else:
  1292. workspaceFile = args.pop(0)
  1293. return (workspaceFile,)
  1294. def main(argv=None):
  1295. #
  1296. # process command-line arguments
  1297. #
  1298. if argv is None:
  1299. argv = sys.argv
  1300. try:
  1301. try:
  1302. opts, args = getopt.getopt(argv[1:], "hw:",
  1303. ["help", "workspace"])
  1304. except getopt.error, msg:
  1305. raise Usage(msg)
  1306. except Usage, err:
  1307. print >> sys.stderr, err.msg
  1308. print >> sys.stderr, "for help use --help"
  1309. printHelp()
  1310. workspaceFile = process_opt(opts, args)[0]
  1311. #
  1312. # run application
  1313. #
  1314. app = GMApp(workspaceFile)
  1315. # suppress wxPython logs
  1316. q = wx.LogNull()
  1317. app.MainLoop()
  1318. if __name__ == "__main__":
  1319. sys.exit(main())