wxgui.py 59 KB

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