wxgui.py 59 KB

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