wxgui.py 58 KB

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