wxgui.py 58 KB

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