wxgui.py 59 KB

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