wxgui.py 59 KB

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