wxgui.py 58 KB

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