wxgui.py 60 KB

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