wxgui.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603
  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. except ImportError:
  46. import wx.lib.customtreectrl as CT
  47. try:
  48. import wx.lib.agw.flatnotebook as FN
  49. except ImportError:
  50. import wx.lib.flatnotebook as FN
  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. self.notebook = FN.FlatNotebook(parent=self, id=wx.ID_ANY, style=nbStyle)
  172. # create displays notebook widget and add it to main notebook page
  173. cbStyle = globalvar.FNPageStyle
  174. self.gm_cb = FN.FlatNotebook(self, id=wx.ID_ANY, style=cbStyle)
  175. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  176. self.notebook.AddPage(self.gm_cb, text=_("Map layers"))
  177. # create command output text area and add it to main notebook page
  178. self.goutput = goutput.GMConsole(self, pageid=1)
  179. self.notebook.AddPage(self.goutput, text=_("Command console"))
  180. # create 'search module' notebook page
  181. self.search = MenuTreeWindow(parent = self)
  182. self.notebook.AddPage(self.search, text = _("Search module"))
  183. # bindings
  184. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  185. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  186. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  187. return self.notebook
  188. def AddNviz(self):
  189. """!Add nviz notebook page"""
  190. self.nviz = nviz_tools.NvizToolWindow(parent = self,
  191. display = self.curr_page.maptree.GetMapDisplay())
  192. self.notebook.AddPage(self.nviz, text = _("3D view"))
  193. self.notebook.SetSelection(self.notebook.GetPageCount() - 1)
  194. def RemoveNviz(self):
  195. """!Remove nviz notebook page"""
  196. # print self.notebook.GetPage(1)
  197. self.notebook.RemovePage(3)
  198. del self.nviz
  199. self.notebook.SetSelection(0)
  200. def WorkspaceChanged(self):
  201. """!Update window title"""
  202. if not self.workspaceChanged:
  203. self.workspaceChanged = True
  204. if self.workspaceFile:
  205. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile) + '*')
  206. def OnGeorectify(self, event):
  207. """!Launch georectifier module
  208. """
  209. georect.GeorectWizard(self)
  210. def OnGModeler(self, event):
  211. """!Launch Graphical Modeler"""
  212. win = gmodeler.ModelFrame(parent = self)
  213. win.CentreOnScreen()
  214. win.Show()
  215. def OnDone(self, returncode):
  216. """Command execution finised"""
  217. if hasattr(self, "model"):
  218. self.model.DeleteIntermediateData(log = self.goutput)
  219. del self.model
  220. self.SetStatusText('')
  221. def OnRunModel(self, event):
  222. """!Run model"""
  223. filename = ''
  224. dlg = wx.FileDialog(parent = self, message=_("Choose model to run"),
  225. defaultDir = os.getcwd(),
  226. wildcard=_("GRASS Model File (*.gxm)|*.gxm"))
  227. if dlg.ShowModal() == wx.ID_OK:
  228. filename = dlg.GetPath()
  229. if not filename:
  230. return
  231. self.model = gmodeler.Model()
  232. self.model.LoadModel(filename)
  233. self.SetStatusText(_('Validating model...'), 0)
  234. result = self.model.Validate()
  235. if result:
  236. dlg = wx.MessageDialog(parent = self,
  237. message = _('Model is not valid. Do you want to '
  238. 'run the model anyway?\n\n%s') % '\n'.join(errList),
  239. caption=_("Run model?"),
  240. style = wx.YES_NO | wx.NO_DEFAULT |
  241. wx.ICON_QUESTION | wx.CENTRE)
  242. ret = dlg.ShowModal()
  243. if ret != wx.ID_YES:
  244. return
  245. self.SetStatusText(_('Running model...'), 0)
  246. self.model.Run(log = self.goutput,
  247. onDone = self.OnDone)
  248. def OnMapsets(self, event):
  249. """
  250. Launch mapset access dialog
  251. """
  252. dlg = preferences.MapsetAccess(parent=self, id=wx.ID_ANY)
  253. dlg.CenterOnScreen()
  254. # if OK is pressed...
  255. if dlg.ShowModal() == wx.ID_OK:
  256. ms = dlg.GetMapsets()
  257. # run g.mapsets with string of accessible mapsets
  258. gcmd.RunCommand('g.mapsets',
  259. parent = self,
  260. mapset = '%s' % ','.join(ms))
  261. def OnRDigit(self, event):
  262. """
  263. Launch raster digitizing module
  264. """
  265. pass
  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. self.goutput.cmd_prompt.SetSTCFocus(True)
  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']:
  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, err:
  513. raise gcmd.GStdError(_("Reading workspace file <%(file)s> failed.\n"
  514. "Invalid file, unable to parse XML document."
  515. "\n\n%(err)s") % { 'file' : filename, 'err': err},
  516. parent = self)
  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. else:
  687. self.OnWorkspaceSaveAs()
  688. def SaveToWorkspaceFile(self, filename):
  689. """!Save layer tree layout to workspace file
  690. Return True on success, False on error
  691. """
  692. try:
  693. file = open(filename, "w")
  694. except IOError:
  695. wx.MessageBox(parent=self,
  696. message=_("Unable to open workspace file <%s> for writing.") % filename,
  697. caption=_("Error"), style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  698. return False
  699. try:
  700. workspace.WriteWorkspaceFile(lmgr=self, file=file)
  701. except StandardError, e:
  702. file.close()
  703. wx.MessageBox(parent=self,
  704. message=_("Writing current settings to workspace file failed (%s)." % e),
  705. caption=_("Error"),
  706. style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
  707. return False
  708. file.close()
  709. return True
  710. def OnWorkspaceClose(self, event = None):
  711. """!Close file with workspace definition
  712. If workspace has been modified ask user to save the changes.
  713. """
  714. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  715. displays = list()
  716. for page in range(0, self.gm_cb.GetPageCount()):
  717. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  718. for display in displays:
  719. display.OnCloseWindow(event)
  720. self.workspaceFile = None
  721. self.workspaceChanged = False
  722. self.SetTitle(self.baseTitle)
  723. self.disp_idx = 0
  724. self.curr_page = None
  725. def RulesCmd(self, event, cmd = ''):
  726. """
  727. Launches dialog for commands that need rules
  728. input and processes rules
  729. """
  730. if event:
  731. cmd = self.GetMenuCmd(event)
  732. if cmd[0] == 'r.colors' or cmd[0] == 'vcolors':
  733. ctable = colorrules.ColorTable(self, cmd=cmd[0])
  734. ctable.Show()
  735. else:
  736. dlg = rules.RulesText(self, cmd=cmd)
  737. dlg.CenterOnScreen()
  738. if dlg.ShowModal() == wx.ID_OK:
  739. gtemp = utils.GetTempfile()
  740. output = open(gtemp, "w")
  741. try:
  742. output.write(dlg.rules)
  743. finally:
  744. output.close()
  745. cmdlist = [cmd[0],
  746. 'input=%s' % dlg.inmap,
  747. 'output=%s' % dlg.outmap,
  748. 'rules=%s' % gtemp]
  749. if dlg.overwrite == True:
  750. cmdlist.append('--o')
  751. dlg.Destroy()
  752. self.goutput.RunCmd(cmdlist)
  753. def OnInstallExtension(self, event):
  754. """!Install extension from GRASS Addons SVN repository"""
  755. win = InstallExtensionWindow(self, size = (550, 400))
  756. win.CentreOnScreen()
  757. win.Show()
  758. def OnPreferences(self, event):
  759. """!General GUI preferences/settings"""
  760. if not self.dialogs['preferences']:
  761. dlg = preferences.PreferencesDialog(parent=self)
  762. self.dialogs['preferences'] = dlg
  763. self.dialogs['preferences'].CenterOnScreen()
  764. self.dialogs['preferences'].ShowModal()
  765. def DispHistogram(self, event):
  766. """
  767. Init histogram display canvas and tools
  768. """
  769. self.histogram = histogram.HistFrame(self,
  770. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  771. style=wx.DEFAULT_FRAME_STYLE)
  772. #show new display
  773. self.histogram.Show()
  774. self.histogram.Refresh()
  775. self.histogram.Update()
  776. def DispProfile(self, event):
  777. """
  778. Init profile canvas and tools
  779. """
  780. self.profile = profile.ProfileFrame(self,
  781. id=wx.ID_ANY, pos=wx.DefaultPosition, size=(400,300),
  782. style=wx.DEFAULT_FRAME_STYLE)
  783. self.profile.Show()
  784. self.profile.Refresh()
  785. self.profile.Update()
  786. def OnMapCalculator(self, event, cmd = ''):
  787. """!Init map calculator for interactive creation of mapcalc statements
  788. """
  789. if event:
  790. cmd = self.GetMenuCmd(event)
  791. win = mapcalculator.MapCalcFrame(parent = self, title = _('GRASS GIS Map Calculator'),
  792. cmd=cmd[0])
  793. win.CentreOnScreen()
  794. win.Show()
  795. def OnMapCalculator3D(self, event, cmd =''):
  796. """!Init map calculator for interactive creation of mapcalc statements
  797. """
  798. if event:
  799. cmd = self.GetMenuCmd(event)
  800. win = mapcalculator.MapCalcFrame(parent = self, title = _('GRASS GIS Map Calculator (3D raster)'),
  801. cmd=cmd[0])
  802. win.CentreOnScreen()
  803. win.Show()
  804. def OnVectorCleaning(self, event, cmd = ''):
  805. """!Init interactive vector cleaning
  806. """
  807. if event:
  808. cmd = self.GetMenuCmd(event)
  809. win = vclean.VectorCleaningFrame(parent = self, cmd = cmd[0])
  810. win.CentreOnScreen()
  811. win.Show()
  812. def OnImportDxfFile(self, event):
  813. """!Convert multiple DXF layers to GRASS vector map layers"""
  814. dlg = gdialogs.DxfImportDialog(parent=self)
  815. dlg.ShowModal()
  816. def OnImportGdalLayers(self, event):
  817. """!Convert multiple GDAL layers to GRASS raster map layers"""
  818. dlg = gdialogs.GdalImportDialog(parent=self)
  819. dlg.ShowModal()
  820. def OnLinkGdalLayers(self, event):
  821. """!Link multiple GDAL layers to GRASS raster map layers"""
  822. dlg = gdialogs.GdalImportDialog(parent=self, link = True)
  823. dlg.ShowModal()
  824. def OnImportOgrLayers(self, event):
  825. """!Convert multiple OGR layers to GRASS vector map layers"""
  826. dlg = gdialogs.GdalImportDialog(parent=self, ogr = True)
  827. dlg.ShowModal()
  828. def OnLinkOgrLayers(self, event):
  829. """!Links multiple OGR layers to GRASS vector map layers"""
  830. dlg = gdialogs.GdalImportDialog(parent=self, ogr = True, link = True)
  831. dlg.ShowModal()
  832. def OnImportWMS(self, event):
  833. """!Import data from OGC WMS server"""
  834. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  835. dlg.CenterOnScreen()
  836. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  837. layers = dlg.GetLayers()
  838. if len(layers.keys()) > 0:
  839. for layer in layers.keys():
  840. cmd = ['r.in.wms',
  841. 'mapserver=%s' % dlg.GetSettings()['server'],
  842. 'layers=%s' % layer,
  843. 'output=%s' % layer]
  844. styles = ','.join(layers[layer])
  845. if styles:
  846. cmd.append('styles=%s' % styles)
  847. self.goutput.RunCmd(cmd, switchPage = True)
  848. else:
  849. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  850. dlg.Destroy()
  851. def OnShowAttributeTable(self, event):
  852. """
  853. Show attribute table of the given vector map layer
  854. """
  855. if not self.curr_page:
  856. self.MsgNoLayerSelected()
  857. return
  858. layer = self.curr_page.maptree.layer_selected
  859. # no map layer selected
  860. if not layer:
  861. self.MsgNoLayerSelected()
  862. return
  863. # available only for vector map layers
  864. try:
  865. maptype = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].type
  866. except:
  867. maptype = None
  868. if not maptype or maptype != 'vector':
  869. wx.MessageBox(parent=self,
  870. message=_("Attribute management is available only "
  871. "for vector maps."),
  872. caption=_("Message"),
  873. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  874. return
  875. if not self.curr_page.maptree.GetPyData(layer)[0]:
  876. return
  877. dcmd = self.curr_page.maptree.GetPyData(layer)[0]['cmd']
  878. if not dcmd:
  879. return
  880. busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
  881. parent=self)
  882. wx.Yield()
  883. dbmanager = dbm.AttributeManager(parent=self, id=wx.ID_ANY,
  884. size=wx.Size(500, 300),
  885. item=layer, log=self.goutput)
  886. busy.Destroy()
  887. # register ATM dialog
  888. self.dialogs['atm'].append(dbmanager)
  889. # show ATM window
  890. dbmanager.Show()
  891. def OnNewDisplay(self, event=None):
  892. """!Create new layer tree and map display instance"""
  893. self.NewDisplay()
  894. def NewDisplay(self, show=True):
  895. """!Create new layer tree, which will
  896. create an associated map display frame
  897. @param show show map display window if True
  898. @return reference to mapdisplay intance
  899. """
  900. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  901. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  902. self.pg_panel = wx.Panel(self.gm_cb, id=wx.ID_ANY, style= wx.EXPAND)
  903. self.gm_cb.AddPage(self.pg_panel, text="Display "+ str(self.disp_idx + 1), select = True)
  904. self.curr_page = self.gm_cb.GetCurrentPage()
  905. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  906. self.curr_page.maptree = layertree.LayerTree(self.curr_page, id=wx.ID_ANY, pos=wx.DefaultPosition,
  907. size=wx.DefaultSize, style=wx.TR_HAS_BUTTONS |
  908. wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
  909. wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
  910. idx=self.disp_idx, lmgr=self, notebook=self.gm_cb,
  911. auimgr=self._auimgr, showMapDisplay=show)
  912. # layout for controls
  913. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  914. cb_boxsizer.Add(self.curr_page.maptree, proportion=1, flag=wx.EXPAND, border=1)
  915. self.curr_page.SetSizer(cb_boxsizer)
  916. cb_boxsizer.Fit(self.curr_page.maptree)
  917. self.curr_page.Layout()
  918. self.curr_page.maptree.Layout()
  919. # use default window layout
  920. if UserSettings.Get(group='general', key='defWindowPos', subkey='enabled') is True:
  921. dim = UserSettings.Get(group='general', key='defWindowPos', subkey='dim')
  922. idx = 4 + self.disp_idx * 4
  923. try:
  924. x, y = map(int, dim.split(',')[idx:idx + 2])
  925. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  926. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  927. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  928. except:
  929. pass
  930. self.disp_idx += 1
  931. return self.curr_page.maptree.mapdisplay
  932. # toolBar button handlers
  933. def OnAddRaster(self, event):
  934. """!Add raster map layer"""
  935. # start new map display if no display is available
  936. if not self.curr_page:
  937. self.NewDisplay(show=False)
  938. self.AddRaster(event)
  939. def OnAddRasterMisc(self, event):
  940. """!Add raster menu"""
  941. # start new map display if no display is available
  942. if not self.curr_page:
  943. self.NewDisplay(show=False)
  944. point = wx.GetMousePosition()
  945. rastmenu = wx.Menu()
  946. # add items to the menu
  947. if self.curr_page.maptree.mapdisplay.toolbars['nviz']:
  948. addrast3d = wx.MenuItem(rastmenu, -1, Icons ["addrast3d"].GetLabel())
  949. addrast3d.SetBitmap(Icons["addrast3d"].GetBitmap (self.iconsize))
  950. rastmenu.AppendItem(addrast3d)
  951. self.Bind(wx.EVT_MENU, self.AddRaster3d, addrast3d)
  952. addshaded = wx.MenuItem(rastmenu, -1, Icons ["addshaded"].GetLabel())
  953. addshaded.SetBitmap(Icons["addshaded"].GetBitmap (self.iconsize))
  954. rastmenu.AppendItem(addshaded)
  955. self.Bind(wx.EVT_MENU, self.AddShaded, addshaded)
  956. addrgb = wx.MenuItem(rastmenu, -1, Icons["addrgb"].GetLabel())
  957. addrgb.SetBitmap(Icons["addrgb"].GetBitmap(self.iconsize))
  958. rastmenu.AppendItem(addrgb)
  959. self.Bind(wx.EVT_MENU, self.AddRGB, addrgb)
  960. addhis = wx.MenuItem(rastmenu, -1, Icons ["addhis"].GetLabel())
  961. addhis.SetBitmap(Icons["addhis"].GetBitmap (self.iconsize))
  962. rastmenu.AppendItem(addhis)
  963. self.Bind(wx.EVT_MENU, self.AddHIS, addhis)
  964. addrastarrow = wx.MenuItem(rastmenu, -1, Icons ["addrarrow"].GetLabel())
  965. addrastarrow.SetBitmap(Icons["addrarrow"].GetBitmap (self.iconsize))
  966. rastmenu.AppendItem(addrastarrow)
  967. self.Bind(wx.EVT_MENU, self.AddRastarrow, addrastarrow)
  968. addrastnums = wx.MenuItem(rastmenu, -1, Icons ["addrnum"].GetLabel())
  969. addrastnums.SetBitmap(Icons["addrnum"].GetBitmap (self.iconsize))
  970. rastmenu.AppendItem(addrastnums)
  971. self.Bind(wx.EVT_MENU, self.AddRastnum, addrastnums)
  972. # Popup the menu. If an item is selected then its handler
  973. # will be called before PopupMenu returns.
  974. self.PopupMenu(rastmenu)
  975. rastmenu.Destroy()
  976. # show map display
  977. self.curr_page.maptree.mapdisplay.Show()
  978. def OnAddVector(self, event):
  979. """!Add vector map layer"""
  980. # start new map display if no display is available
  981. if not self.curr_page:
  982. self.NewDisplay(show=False)
  983. self.AddVector(event)
  984. def OnAddVectorMisc(self, event):
  985. """!Add vector menu"""
  986. # start new map display if no display is available
  987. if not self.curr_page:
  988. self.NewDisplay(show=False)
  989. point = wx.GetMousePosition()
  990. vectmenu = wx.Menu()
  991. addtheme = wx.MenuItem(vectmenu, -1, Icons["addthematic"].GetLabel())
  992. addtheme.SetBitmap(Icons["addthematic"].GetBitmap(self.iconsize))
  993. vectmenu.AppendItem(addtheme)
  994. self.Bind(wx.EVT_MENU, self.AddThemeMap, addtheme)
  995. addchart = wx.MenuItem(vectmenu, -1, Icons["addchart"].GetLabel())
  996. addchart.SetBitmap(Icons["addchart"].GetBitmap(self.iconsize))
  997. vectmenu.AppendItem(addchart)
  998. self.Bind(wx.EVT_MENU, self.AddThemeChart, addchart)
  999. # Popup the menu. If an item is selected then its handler
  1000. # will be called before PopupMenu returns.
  1001. self.PopupMenu(vectmenu)
  1002. vectmenu.Destroy()
  1003. # show map display
  1004. self.curr_page.maptree.mapdisplay.Show()
  1005. def OnAddOverlay(self, event):
  1006. """!Add decoration overlay menu"""
  1007. # start new map display if no display is available
  1008. if not self.curr_page:
  1009. self.NewDisplay(show=False)
  1010. point = wx.GetMousePosition()
  1011. ovlmenu = wx.Menu()
  1012. addgrid = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgrid"].GetLabel())
  1013. addgrid.SetBitmap(Icons["addgrid"].GetBitmap(self.iconsize))
  1014. ovlmenu.AppendItem(addgrid)
  1015. self.Bind(wx.EVT_MENU, self.AddGrid, addgrid)
  1016. addlabels = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addlabels"].GetLabel())
  1017. addlabels.SetBitmap(Icons["addlabels"].GetBitmap(self.iconsize))
  1018. ovlmenu.AppendItem(addlabels)
  1019. self.Bind(wx.EVT_MENU, self.OnAddLabels, addlabels)
  1020. addgeodesic = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addgeodesic"].GetLabel())
  1021. addgeodesic.SetBitmap(Icons["addgeodesic"].GetBitmap(self.iconsize))
  1022. ovlmenu.AppendItem(addgeodesic)
  1023. self.Bind(wx.EVT_MENU, self.AddGeodesic, addgeodesic)
  1024. addrhumb = wx.MenuItem(ovlmenu, wx.ID_ANY, Icons["addrhumb"].GetLabel())
  1025. addrhumb.SetBitmap(Icons["addrhumb"].GetBitmap(self.iconsize))
  1026. ovlmenu.AppendItem(addrhumb)
  1027. self.Bind(wx.EVT_MENU, self.AddRhumb, addrhumb)
  1028. # Popup the menu. If an item is selected then its handler
  1029. # will be called before PopupMenu returns.
  1030. self.PopupMenu(ovlmenu)
  1031. ovlmenu.Destroy()
  1032. # show map display
  1033. self.curr_page.maptree.mapdisplay.Show()
  1034. def AddRaster(self, event):
  1035. self.notebook.SetSelection(0)
  1036. self.curr_page.maptree.AddLayer('raster')
  1037. def AddRaster3d(self, event):
  1038. self.notebook.SetSelection(0)
  1039. self.curr_page.maptree.AddLayer('3d-raster')
  1040. def AddRGB(self, event):
  1041. """!Add RGB layer"""
  1042. self.notebook.SetSelection(0)
  1043. self.curr_page.maptree.AddLayer('rgb')
  1044. def AddHIS(self, event):
  1045. """!Add HIS layer"""
  1046. self.notebook.SetSelection(0)
  1047. self.curr_page.maptree.AddLayer('his')
  1048. def AddShaded(self, event):
  1049. """!Add shaded relief map layer"""
  1050. self.notebook.SetSelection(0)
  1051. self.curr_page.maptree.AddLayer('shaded')
  1052. def AddRastarrow(self, event):
  1053. """!Add raster flow arrows map"""
  1054. self.notebook.SetSelection(0)
  1055. self.curr_page.maptree.AddLayer('rastarrow')
  1056. def AddRastnum(self, event):
  1057. """!Add raster map with cell numbers"""
  1058. self.notebook.SetSelection(0)
  1059. self.curr_page.maptree.AddLayer('rastnum')
  1060. def AddVector(self, event):
  1061. """!Add vector layer"""
  1062. self.notebook.SetSelection(0)
  1063. self.curr_page.maptree.AddLayer('vector')
  1064. def AddThemeMap(self, event):
  1065. """!Add thematic map layer"""
  1066. self.notebook.SetSelection(0)
  1067. self.curr_page.maptree.AddLayer('thememap')
  1068. def AddThemeChart(self, event):
  1069. """!Add thematic chart layer"""
  1070. self.notebook.SetSelection(0)
  1071. self.curr_page.maptree.AddLayer('themechart')
  1072. def OnAddCommand(self, event):
  1073. """!Add command line layer"""
  1074. # start new map display if no display is available
  1075. if not self.curr_page:
  1076. self.NewDisplay(show=False)
  1077. self.notebook.SetSelection(0)
  1078. self.curr_page.maptree.AddLayer('command')
  1079. # show map display
  1080. self.curr_page.maptree.mapdisplay.Show()
  1081. def OnAddGroup(self, event):
  1082. """!Add layer group"""
  1083. # start new map display if no display is available
  1084. if not self.curr_page:
  1085. self.NewDisplay(show=False)
  1086. self.notebook.SetSelection(0)
  1087. self.curr_page.maptree.AddLayer('group')
  1088. # show map display
  1089. self.curr_page.maptree.mapdisplay.Show()
  1090. def AddGrid(self, event):
  1091. """!Add layer grid"""
  1092. self.notebook.SetSelection(0)
  1093. self.curr_page.maptree.AddLayer('grid')
  1094. def AddGeodesic(self, event):
  1095. """!Add layer geodesic"""
  1096. self.notebook.SetSelection(0)
  1097. self.curr_page.maptree.AddLayer('geodesic')
  1098. def AddRhumb(self, event):
  1099. """!Add layer rhumb"""
  1100. self.notebook.SetSelection(0)
  1101. self.curr_page.maptree.AddLayer('rhumb')
  1102. def OnAddLabels(self, event):
  1103. """!Add layer vector labels"""
  1104. # start new map display if no display is available
  1105. if not self.curr_page:
  1106. self.NewDisplay(show=False)
  1107. self.notebook.SetSelection(0)
  1108. self.curr_page.maptree.AddLayer('labels')
  1109. # show map display
  1110. self.curr_page.maptree.mapdisplay.Show()
  1111. def OnDeleteLayer(self, event):
  1112. """
  1113. Delete selected map display layer in GIS Manager tree widget
  1114. """
  1115. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1116. self.MsgNoLayerSelected()
  1117. return
  1118. if UserSettings.Get(group='manager', key='askOnRemoveLayer', subkey='enabled'):
  1119. layerName = ''
  1120. for item in self.curr_page.maptree.GetSelections():
  1121. name = str(self.curr_page.maptree.GetItemText(item))
  1122. idx = name.find('(opacity')
  1123. if idx > -1:
  1124. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1125. else:
  1126. layerName += '<' + name + '>,\n'
  1127. layerName = layerName.rstrip(',\n')
  1128. if len(layerName) > 2: # <>
  1129. message = _("Do you want to remove map layer(s)\n%s\n"
  1130. "from layer tree?") % layerName
  1131. else:
  1132. message = _("Do you want to remove selected map layer(s) "
  1133. "from layer tree?")
  1134. dlg = wx.MessageDialog (parent=self, message=message,
  1135. caption=_("Remove map layer"),
  1136. style=wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
  1137. if dlg.ShowModal() in [wx.ID_NO, wx.ID_CANCEL]:
  1138. dlg.Destroy()
  1139. return
  1140. dlg.Destroy()
  1141. for layer in self.curr_page.maptree.GetSelections():
  1142. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1143. self.curr_page.maptree.DeleteChildren(layer)
  1144. self.curr_page.maptree.Delete(layer)
  1145. def OnKeyDown(self, event):
  1146. """!Key pressed"""
  1147. kc = event.GetKeyCode()
  1148. if event.ControlDown():
  1149. if kc == wx.WXK_TAB:
  1150. # switch layer list / command output
  1151. if self.notebook.GetSelection() == 0:
  1152. self.notebook.SetSelection(1)
  1153. else:
  1154. self.notebook.SetSelection(0)
  1155. try:
  1156. ckc = chr(kc)
  1157. except ValueError:
  1158. event.Skip()
  1159. return
  1160. if event.CtrlDown():
  1161. if kc == 'R':
  1162. self.OnAddRaster(None)
  1163. elif kc == 'V':
  1164. self.OnAddVector(None)
  1165. event.Skip()
  1166. def OnQuit(self, event):
  1167. """!Quit GRASS session (wxGUI and shell)"""
  1168. # quit wxGUI session
  1169. self.OnCloseWindow(event)
  1170. # quit GRASS shell
  1171. try:
  1172. pid = int(os.environ['GIS_LOCK'])
  1173. except (KeyError, ValueError):
  1174. sys.stderr.write('\n')
  1175. sys.stderr.write(_("WARNING: Unable to quit GRASS, unknown GIS_LOCK"))
  1176. return
  1177. os.kill(pid, signal.SIGQUIT)
  1178. def OnCloseWindow(self, event):
  1179. """!Cleanup when wxGUI is quit"""
  1180. if not self.curr_page:
  1181. self._auimgr.UnInit()
  1182. self.Destroy()
  1183. return
  1184. maptree = self.curr_page.maptree
  1185. if self.workspaceChanged and \
  1186. UserSettings.Get(group='manager', key='askOnQuit', subkey='enabled'):
  1187. if self.workspaceFile:
  1188. message = _("Do you want to save changes in the workspace?")
  1189. else:
  1190. message = _("Do you want to store current settings "
  1191. "to workspace file?")
  1192. # ask user to save current settings
  1193. if maptree.GetCount() > 0:
  1194. dlg = wx.MessageDialog(self,
  1195. message=message,
  1196. caption=_("Quit GRASS GUI"),
  1197. style=wx.YES_NO | wx.YES_DEFAULT |
  1198. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1199. ret = dlg.ShowModal()
  1200. if ret == wx.ID_YES:
  1201. if not self.workspaceFile:
  1202. self.OnWorkspaceSaveAs()
  1203. else:
  1204. self.SaveToWorkspaceFile(self.workspaceFile)
  1205. elif ret == wx.ID_CANCEL:
  1206. event.Veto()
  1207. dlg.Destroy()
  1208. return
  1209. dlg.Destroy()
  1210. # don't ask any more...
  1211. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1212. value = False)
  1213. for page in range(self.gm_cb.GetPageCount()):
  1214. self.gm_cb.GetPage(0).maptree.mapdisplay.OnCloseWindow(event)
  1215. self.gm_cb.DeleteAllPages()
  1216. self._auimgr.UnInit()
  1217. self.Destroy()
  1218. def MsgNoLayerSelected(self):
  1219. """!Show dialog message 'No layer selected'"""
  1220. wx.MessageBox(parent=self,
  1221. message=_("No map layer selected. Operation cancelled."),
  1222. caption=_("Message"),
  1223. style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1224. class GMApp(wx.App):
  1225. def __init__(self, workspace = None):
  1226. """!Main GUI class.
  1227. @param workspace path to the workspace file
  1228. """
  1229. self.workspaceFile = workspace
  1230. # call parent class initializer
  1231. wx.App.__init__(self, False)
  1232. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  1233. def OnInit(self):
  1234. """!Initialize all available image handlers
  1235. @return True
  1236. """
  1237. wx.InitAllImageHandlers()
  1238. # create splash screen
  1239. introImagePath = os.path.join(globalvar.ETCWXDIR, "images", "grass_splash.png")
  1240. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1241. introBmp = introImage.ConvertToBitmap()
  1242. wx.SplashScreen (bitmap=introBmp, splashStyle=wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1243. milliseconds=2000, parent=None, id=wx.ID_ANY)
  1244. wx.Yield()
  1245. # create and show main frame
  1246. mainframe = GMFrame(parent=None, id=wx.ID_ANY,
  1247. workspace = self.workspaceFile)
  1248. mainframe.Show()
  1249. self.SetTopWindow(mainframe)
  1250. return True
  1251. class Usage(Exception):
  1252. def __init__(self, msg):
  1253. self.msg = msg
  1254. def printHelp():
  1255. """!Print program help"""
  1256. print >> sys.stderr, "Usage:"
  1257. print >> sys.stderr, " python wxgui.py [options]"
  1258. print >> sys.stderr, "%sOptions:" % os.linesep
  1259. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1260. sys.exit(0)
  1261. def process_opt(opts, args):
  1262. """!Process command-line arguments"""
  1263. workspaceFile = None
  1264. for o, a in opts:
  1265. if o in ("-h", "--help"):
  1266. printHelp()
  1267. if o in ("-w", "--workspace"):
  1268. if a != '':
  1269. workspaceFile = str(a)
  1270. else:
  1271. workspaceFile = args.pop(0)
  1272. return (workspaceFile,)
  1273. def main(argv=None):
  1274. #
  1275. # process command-line arguments
  1276. #
  1277. if argv is None:
  1278. argv = sys.argv
  1279. try:
  1280. try:
  1281. opts, args = getopt.getopt(argv[1:], "hw:",
  1282. ["help", "workspace"])
  1283. except getopt.error, msg:
  1284. raise Usage(msg)
  1285. except Usage, err:
  1286. print >> sys.stderr, err.msg
  1287. print >> sys.stderr, "for help use --help"
  1288. printHelp()
  1289. workspaceFile = process_opt(opts, args)[0]
  1290. #
  1291. # run application
  1292. #
  1293. app = GMApp(workspaceFile)
  1294. # suppress wxPython logs
  1295. q = wx.LogNull()
  1296. app.MainLoop()
  1297. if __name__ == "__main__":
  1298. sys.exit(main())