wxgui.py 58 KB

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