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