wxgui.py 59 KB

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