wxgui.py 59 KB

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