wxgui.py 58 KB

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