wxgui.py 61 KB

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