wxgui.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745
  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-2011 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. @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
  17. """
  18. import sys
  19. import os
  20. import time
  21. import string
  22. import getopt
  23. import platform
  24. import signal
  25. import tempfile
  26. try:
  27. import xml.etree.ElementTree as etree
  28. except ImportError:
  29. import elementtree.ElementTree as etree # Python <= 2.4
  30. from gui_modules import globalvar
  31. import wx
  32. import wx.aui
  33. import wx.combo
  34. import wx.html
  35. import wx.stc
  36. try:
  37. import wx.lib.agw.customtreectrl as CT
  38. import wx.lib.agw.flatnotebook as FN
  39. except ImportError:
  40. import wx.lib.customtreectrl as CT
  41. import wx.lib.flatnotebook as FN
  42. try:
  43. import wx.lib.agw.advancedsplash as SC
  44. except ImportError:
  45. SC = None
  46. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  47. from grass.script import core as grass
  48. from gui_modules import utils
  49. from gui_modules import preferences
  50. from gui_modules import layertree
  51. from gui_modules import mapdisp
  52. from gui_modules import menudata
  53. from gui_modules import menuform
  54. from gui_modules import histogram
  55. from gui_modules import profile
  56. from gui_modules import mcalc_builder as mapcalculator
  57. from gui_modules import gcmd
  58. from gui_modules import dbm
  59. from gui_modules import workspace
  60. from gui_modules import goutput
  61. from gui_modules import gdialogs
  62. from gui_modules import colorrules
  63. from gui_modules import ogc_services
  64. from gui_modules import prompt
  65. from gui_modules import menu
  66. from gui_modules import gmodeler
  67. from gui_modules import vclean
  68. from gui_modules import nviz_tools
  69. from gui_modules import psmap
  70. from gui_modules.debug import Debug
  71. from gui_modules.ghelp import MenuTreeWindow, AboutWindow, InstallExtensionWindow
  72. from gui_modules.toolbars import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar,\
  73. LMMiscToolbar, LMVectorToolbar, LMNvizToolbar
  74. from gui_modules.gpyshell import PyShellWindow
  75. from icons.icon import Icons
  76. UserSettings = preferences.globalSettings
  77. class GMFrame(wx.Frame):
  78. """!Layer Manager frame with notebook widget for controlling GRASS
  79. GIS. Includes command console page for typing GRASS (and other)
  80. commands, tree widget page for managing map layers.
  81. """
  82. def __init__(self, parent, id = wx.ID_ANY, title = _("GRASS GIS Layer Manager"),
  83. workspace = None,
  84. size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
  85. self.parent = parent
  86. self.baseTitle = title
  87. self.iconsize = (16, 16)
  88. wx.Frame.__init__(self, parent = parent, id = id, size = size,
  89. style = style, **kwargs)
  90. self.SetTitle(self.baseTitle)
  91. self.SetName("LayerManager")
  92. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  93. self._auimgr = wx.aui.AuiManager(self)
  94. # initialize variables
  95. self.disp_idx = 0 # index value for map displays and layer trees
  96. self.curr_page = None # currently selected page for layer tree notebook
  97. self.curr_pagenum = None # currently selected page number for layer tree notebook
  98. self.workspaceFile = workspace # workspace file
  99. self.workspaceChanged = False # track changes in workspace
  100. self.georectifying = None # reference to GCP class or None
  101. self.gcpmanagement = None # reference to GCP class or None
  102. # list of open dialogs
  103. self.dialogs = dict()
  104. self.dialogs['preferences'] = None
  105. self.dialogs['atm'] = list()
  106. # creating widgets
  107. self._createMenuBar()
  108. self.statusbar = self.CreateStatusBar(number = 1)
  109. self.notebook = self._createNoteBook()
  110. self.toolbars = { 'workspace' : LMWorkspaceToolbar(parent = self),
  111. 'data' : LMDataToolbar(parent = self),
  112. 'tools' : LMToolsToolbar(parent = self),
  113. 'misc' : LMMiscToolbar(parent = self),
  114. 'vector' : LMVectorToolbar(parent = self),
  115. 'nviz' : LMNvizToolbar(parent = self)}
  116. self._toolbarsData = { 'workspace' : ("toolbarWorkspace", # name
  117. _("Workspace Toolbar"), # caption
  118. 1), # row
  119. 'data' : ("toolbarData",
  120. _("Data Toolbar"),
  121. 1),
  122. 'misc' : ("toolbarMisc",
  123. _("Misc Toolbar"),
  124. 2),
  125. 'tools' : ("toolbarTools",
  126. _("Tools Toolbar"),
  127. 2),
  128. 'vector' : ("toolbarVector",
  129. _("Vector Toolbar"),
  130. 2),
  131. 'nviz' : ("toolbarNviz",
  132. _("3D view Toolbar"),
  133. 2),
  134. }
  135. if sys.platform == 'win32':
  136. self._toolbarsList = ('workspace', 'data',
  137. 'vector', 'tools', 'misc', 'nviz')
  138. else:
  139. self._toolbarsList = ('data', 'workspace',
  140. 'nviz', 'misc', 'tools', 'vector')
  141. for toolbar in self._toolbarsList:
  142. name, caption, row = self._toolbarsData[toolbar]
  143. self._auimgr.AddPane(self.toolbars[toolbar],
  144. wx.aui.AuiPaneInfo().
  145. Name(name).Caption(caption).
  146. ToolbarPane().Top().Row(row).
  147. LeftDockable(False).RightDockable(False).
  148. BottomDockable(False).TopDockable(True).
  149. CloseButton(False).Layer(2).
  150. BestSize((self.toolbars[toolbar].GetBestSize())))
  151. self._auimgr.GetPane('toolbarNviz').Hide()
  152. # bindings
  153. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  154. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  155. # minimal frame size
  156. self.SetMinSize((500, 400))
  157. # AUI stuff
  158. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  159. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  160. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  161. self._auimgr.Update()
  162. wx.CallAfter(self.notebook.SetSelectionByName, 'layers')
  163. # use default window layout ?
  164. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  165. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  166. try:
  167. x, y = map(int, dim.split(',')[0:2])
  168. w, h = map(int, dim.split(',')[2:4])
  169. self.SetPosition((x, y))
  170. self.SetSize((w, h))
  171. except:
  172. pass
  173. else:
  174. self.Centre()
  175. self.Layout()
  176. self.Show()
  177. # load workspace file if requested
  178. if self.workspaceFile:
  179. # load given workspace file
  180. if self.LoadWorkspaceFile(self.workspaceFile):
  181. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  182. else:
  183. self.workspaceFile = None
  184. else:
  185. # start default initial display
  186. self.NewDisplay(show = False)
  187. # show map display widnow
  188. # -> OnSize() -> UpdateMap()
  189. if self.curr_page and not self.curr_page.maptree.mapdisplay.IsShown():
  190. self.curr_page.maptree.mapdisplay.Show()
  191. # redirect stderr to log area
  192. self.goutput.Redirect()
  193. # fix goutput's pane size
  194. self.goutput.SetSashPosition(int(self.GetSize()[1] * .45))
  195. self.workspaceChanged = False
  196. # start with layer manager on top
  197. if self.curr_page:
  198. self.curr_page.maptree.mapdisplay.Raise()
  199. wx.CallAfter(self.Raise)
  200. def _createMenuBar(self):
  201. """!Creates menu bar"""
  202. self.menubar = menu.Menu(parent = self, data = menudata.ManagerData())
  203. self.SetMenuBar(self.menubar)
  204. self.menucmd = self.menubar.GetCmd()
  205. def _setCopyingOfSelectedText(self):
  206. copy = UserSettings.Get(group = 'manager', key = 'copySelectedTextToClipboard', subkey = 'enabled')
  207. self.goutput.SetCopyingOfSelectedText(copy)
  208. def IsPaneShown(self, name):
  209. """!Check if pane (toolbar, ...) of given name is currently shown"""
  210. if self._auimgr.GetPane(name).IsOk():
  211. return self._auimgr.GetPane(name).IsShown()
  212. return False
  213. def _createNoteBook(self):
  214. """!Creates notebook widgets"""
  215. self.notebook = menuform.GNotebook(parent = self, style = globalvar.FNPageDStyle)
  216. # create displays notebook widget and add it to main notebook page
  217. cbStyle = globalvar.FNPageStyle
  218. if globalvar.hasAgw:
  219. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, agwStyle = cbStyle)
  220. else:
  221. self.gm_cb = FN.FlatNotebook(self, id = wx.ID_ANY, style = cbStyle)
  222. self.gm_cb.SetTabAreaColour(globalvar.FNPageColor)
  223. self.notebook.AddPage(page = self.gm_cb, text = _("Map layers"), name = 'layers')
  224. # create 'command output' text area
  225. self.goutput = goutput.GMConsole(self)
  226. self.notebook.AddPage(page = self.goutput, text = _("Command console"), name = 'output')
  227. self._setCopyingOfSelectedText()
  228. # create 'search module' notebook page
  229. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'search'):
  230. self.search = MenuTreeWindow(parent = self)
  231. self.notebook.AddPage(page = self.search, text = _("Search module"), name = 'search')
  232. else:
  233. self.search = None
  234. # create 'python shell' notebook page
  235. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'pyshell'):
  236. self.pyshell = PyShellWindow(parent = self)
  237. self.notebook.AddPage(page = self.pyshell, text = _("Python shell"), name = 'pyshell')
  238. else:
  239. self.pyshell = None
  240. # bindings
  241. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  242. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  243. self.gm_cb.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  244. return self.notebook
  245. def AddNvizTools(self):
  246. """!Add nviz notebook page"""
  247. Debug.msg(5, "GMFrame.AddNvizTools()")
  248. # show toolbar
  249. self._auimgr.GetPane('toolbarNviz').Show()
  250. # reorder other toolbars
  251. for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc','toolbarNviz')):
  252. self._auimgr.GetPane(toolbar).Row(2).Position(pos)
  253. self._auimgr.Update()
  254. # create nviz tools tab
  255. self.nviz = nviz_tools.NvizToolWindow(parent = self,
  256. display = self.curr_page.maptree.GetMapDisplay())
  257. idx = self.notebook.GetPageIndexByName('layers')
  258. self.notebook.InsertPage(indx = idx + 1, page = self.nviz, text = _("3D view"), name = 'nviz')
  259. self.notebook.SetSelectionByName('nviz')
  260. def RemoveNvizTools(self):
  261. """!Remove nviz notebook page"""
  262. # if more mapwindow3D were possible, check here if nb page should be removed
  263. self.notebook.SetSelectionByName('layers')
  264. self.notebook.RemovePage(self.notebook.GetPageIndexByName('nviz'))
  265. del self.nviz
  266. # hide toolbar
  267. self._auimgr.GetPane('toolbarNviz').Hide()
  268. for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc')):
  269. self._auimgr.GetPane(toolbar).Row(2).Position(pos)
  270. self._auimgr.Update()
  271. def WorkspaceChanged(self):
  272. """!Update window title"""
  273. if not self.workspaceChanged:
  274. self.workspaceChanged = True
  275. if self.workspaceFile:
  276. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile) + '*')
  277. def OnLocationWizard(self, event):
  278. """!Launch location wizard"""
  279. from gui_modules import location_wizard
  280. gisdbase = grass.gisenv()['GISDBASE']
  281. gWizard = location_wizard.LocationWizard(parent = self,
  282. grassdatabase = gisdbase)
  283. if gWizard.location != None:
  284. dlg = wx.MessageDialog(parent = self,
  285. message = _('Location <%s> created.\n\n'
  286. 'Do you want to switch to the '
  287. 'new location?') % gWizard.location,
  288. caption=_("Switch to new location?"),
  289. style = wx.YES_NO | wx.NO_DEFAULT |
  290. wx.ICON_QUESTION | wx.CENTRE)
  291. ret = dlg.ShowModal()
  292. if ret == wx.ID_YES:
  293. gcmd.RunCommand("g.gisenv",
  294. set = "LOCATION_NAME=%s" % gWizard.location)
  295. gcmd.RunCommand("g.gisenv",
  296. set = "MAPSET=PERMANENT")
  297. dlg.Destroy()
  298. def OnSettingsChanged(self, event):
  299. """!Here can be functions which have to be called after EVT_SETTINGS_CHANGED.
  300. Now only set copying of selected text to clipboard (in goutput).
  301. """
  302. ### self._createMenuBar() # bug when menu is re-created on the fly
  303. self._setCopyingOfSelectedText()
  304. def OnGCPManager(self, event):
  305. """!Launch georectifier module
  306. """
  307. from gui_modules import gcpmanager
  308. gcpmanager.GCPWizard(self)
  309. def OnGModeler(self, event):
  310. """!Launch Graphical Modeler"""
  311. win = gmodeler.ModelFrame(parent = self)
  312. win.CentreOnScreen()
  313. win.Show()
  314. def OnPsMap(self, event):
  315. """!Launch Cartographic Composer
  316. """
  317. win = psmap.PsMapFrame(parent = self)
  318. win.CentreOnScreen()
  319. win.Show()
  320. def OnRStream(self, event):
  321. """!GSoC's r.stream.* interface for testing
  322. """
  323. try:
  324. from gui_modules import rstream
  325. except:
  326. gcmd.GError(parent = self.parent,
  327. message = _("RStream Utility is not available. You can install it by %s") % \
  328. 'g.extension -s extension=wx.stream')
  329. return
  330. win = rstream.RStreamFrame(parent = self)
  331. win.CentreOnScreen()
  332. win.Show()
  333. def OnDone(self, cmd, returncode):
  334. """Command execution finised"""
  335. if hasattr(self, "model"):
  336. self.model.DeleteIntermediateData(log = self.goutput)
  337. del self.model
  338. self.SetStatusText('')
  339. def OnRunModel(self, event):
  340. """!Run model"""
  341. filename = ''
  342. dlg = wx.FileDialog(parent = self, message =_("Choose model to run"),
  343. defaultDir = os.getcwd(),
  344. wildcard = _("GRASS Model File (*.gxm)|*.gxm"))
  345. if dlg.ShowModal() == wx.ID_OK:
  346. filename = dlg.GetPath()
  347. if not filename:
  348. dlg.Destroy()
  349. return
  350. self.model = gmodeler.Model()
  351. self.model.LoadModel(filename)
  352. self.model.Run(log = self.goutput, onDone = self.OnDone, parent = self)
  353. dlg.Destroy()
  354. def OnMapsets(self, event):
  355. """!Launch mapset access dialog
  356. """
  357. dlg = preferences.MapsetAccess(parent = self, id = wx.ID_ANY)
  358. dlg.CenterOnScreen()
  359. if dlg.ShowModal() == wx.ID_OK:
  360. ms = dlg.GetMapsets()
  361. gcmd.RunCommand('g.mapsets',
  362. parent = self,
  363. mapset = '%s' % ','.join(ms))
  364. def OnCBPageChanged(self, event):
  365. """!Page in notebook (display) changed"""
  366. old_pgnum = event.GetOldSelection()
  367. new_pgnum = event.GetSelection()
  368. self.curr_page = self.gm_cb.GetCurrentPage()
  369. self.curr_pagenum = self.gm_cb.GetSelection()
  370. try:
  371. self.curr_page.maptree.mapdisplay.SetFocus()
  372. self.curr_page.maptree.mapdisplay.Raise()
  373. except:
  374. pass
  375. event.Skip()
  376. def OnPageChanged(self, event):
  377. """!Page in notebook changed"""
  378. page = event.GetSelection()
  379. if page == self.notebook.GetPageIndexByName('output'):
  380. # remove '(...)'
  381. self.notebook.SetPageText(page, _("Command console"))
  382. wx.CallAfter(self.goutput.cmd_prompt.SetFocus)
  383. self.SetStatusText('', 0)
  384. event.Skip()
  385. def OnCBPageClosed(self, event):
  386. """!Page of notebook closed
  387. Also close associated map display
  388. """
  389. if UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  390. maptree = self.curr_page.maptree
  391. if self.workspaceFile:
  392. message = _("Do you want to save changes in the workspace?")
  393. else:
  394. message = _("Do you want to store current settings "
  395. "to workspace file?")
  396. # ask user to save current settings
  397. if maptree.GetCount() > 0:
  398. dlg = wx.MessageDialog(self,
  399. message = message,
  400. caption = _("Close Map Display %d") % (self.curr_pagenum + 1),
  401. style = wx.YES_NO | wx.YES_DEFAULT |
  402. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  403. ret = dlg.ShowModal()
  404. if ret == wx.ID_YES:
  405. if not self.workspaceFile:
  406. self.OnWorkspaceSaveAs()
  407. else:
  408. self.SaveToWorkspaceFile(self.workspaceFile)
  409. elif ret == wx.ID_CANCEL:
  410. event.Veto()
  411. dlg.Destroy()
  412. return
  413. dlg.Destroy()
  414. self.gm_cb.GetPage(event.GetSelection()).maptree.Map.Clean()
  415. self.gm_cb.GetPage(event.GetSelection()).maptree.Close(True)
  416. self.curr_page = None
  417. event.Skip()
  418. def GetLayerTree(self):
  419. """!Get current layer tree"""
  420. return self.curr_page.maptree
  421. def GetLogWindow(self):
  422. """!Get widget for command output"""
  423. return self.goutput
  424. def GetMenuCmd(self, event):
  425. """!Get GRASS command from menu item
  426. Return command as a list"""
  427. layer = None
  428. if event:
  429. cmd = self.menucmd[event.GetId()]
  430. try:
  431. cmdlist = cmd.split(' ')
  432. except: # already list?
  433. cmdlist = cmd
  434. # check list of dummy commands for GUI modules that do not have GRASS
  435. # bin modules or scripts.
  436. if cmd in ['vcolors', 'r.mapcalc', 'r3.mapcalc']:
  437. return cmdlist
  438. try:
  439. layer = self.curr_page.maptree.layer_selected
  440. name = self.curr_page.maptree.GetPyData(layer)[0]['maplayer'].name
  441. type = self.curr_page.maptree.GetPyData(layer)[0]['type']
  442. except:
  443. layer = None
  444. if layer and len(cmdlist) == 1: # only if no paramaters given
  445. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  446. (type == 'vector' and cmdlist[0][0] == 'v'):
  447. input = menuform.GUI().GetCommandInputMapParamKey(cmdlist[0])
  448. if input:
  449. cmdlist.append("%s=%s" % (input, name))
  450. return cmdlist
  451. def RunMenuCmd(self, event = None, cmd = []):
  452. """!Run command selected from menu"""
  453. if event:
  454. cmd = self.GetMenuCmd(event)
  455. self.goutput.RunCmd(cmd, switchPage = False)
  456. def OnMenuCmd(self, event = None, cmd = []):
  457. """!Parse command selected from menu"""
  458. if event:
  459. cmd = self.GetMenuCmd(event)
  460. menuform.GUI(parent = self).ParseCommand(cmd)
  461. def OnVDigit(self, event):
  462. """!Start vector digitizer
  463. """
  464. if not self.curr_page:
  465. self.MsgNoLayerSelected()
  466. return
  467. tree = self.GetLayerTree()
  468. layer = tree.layer_selected
  469. # no map layer selected
  470. if not layer:
  471. self.MsgNoLayerSelected()
  472. return
  473. # available only for vector map layers
  474. try:
  475. mapLayer = tree.GetPyData(layer)[0]['maplayer']
  476. except:
  477. mapLayer = None
  478. if not mapLayer or mapLayer.GetType() != 'vector':
  479. gcmd.GMessage(parent = self,
  480. message = _("Selected map layer is not vector."))
  481. return
  482. if mapLayer.GetMapset() != grass.gisenv()['MAPSET']:
  483. gcmd.GMessage(parent = self,
  484. message = _("Editing is allowed only for vector maps from the "
  485. "current mapset."))
  486. return
  487. if not tree.GetPyData(layer)[0]:
  488. return
  489. dcmd = tree.GetPyData(layer)[0]['cmd']
  490. if not dcmd:
  491. return
  492. tree.OnStartEditing(None)
  493. def OnRunScript(self, event):
  494. """!Run script"""
  495. # open dialog and choose script file
  496. dlg = wx.FileDialog(parent = self, message = _("Choose script file to run"),
  497. defaultDir = os.getcwd(),
  498. wildcard = _("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
  499. filename = None
  500. if dlg.ShowModal() == wx.ID_OK:
  501. filename = dlg.GetPath()
  502. if not filename:
  503. return False
  504. if not os.path.exists(filename):
  505. gcmd.GError(parent = self,
  506. message = _("Script file '%s' doesn't exist. "
  507. "Operation cancelled.") % filename)
  508. return
  509. self.goutput.WriteCmdLog(_("Launching script '%s'...") % filename)
  510. self.goutput.RunCmd([filename], switchPage = True)
  511. def OnChangeLocation(self, event):
  512. """Change current location"""
  513. dlg = gdialogs.LocationDialog(parent = self)
  514. if dlg.ShowModal() == wx.ID_OK:
  515. location, mapset = dlg.GetValues()
  516. if location and mapset:
  517. ret = gcmd.RunCommand("g.gisenv",
  518. set = "LOCATION_NAME=%s" % location)
  519. ret += gcmd.RunCommand("g.gisenv",
  520. set = "MAPSET=%s" % mapset)
  521. if ret > 0:
  522. wx.MessageBox(parent = self,
  523. message = _("Unable to switch to location <%(loc)s> mapset <%(mapset)s>.") % \
  524. { 'loc' : location, 'mapset' : mapset },
  525. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  526. else:
  527. # close workspace
  528. self.OnWorkspaceClose()
  529. self.OnWorkspaceNew()
  530. wx.MessageBox(parent = self,
  531. message = _("Current location is <%(loc)s>.\n"
  532. "Current mapset is <%(mapset)s>.") % \
  533. { 'loc' : location, 'mapset' : mapset },
  534. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  535. def OnChangeMapset(self, event):
  536. """Change current mapset"""
  537. dlg = gdialogs.MapsetDialog(parent = self)
  538. if dlg.ShowModal() == wx.ID_OK:
  539. mapset = dlg.GetMapset()
  540. if mapset:
  541. if gcmd.RunCommand("g.gisenv",
  542. set = "MAPSET=%s" % mapset) != 0:
  543. wx.MessageBox(parent = self,
  544. message = _("Unable to switch to mapset <%s>.") % mapset,
  545. caption = _("Error"), style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
  546. else:
  547. wx.MessageBox(parent = self,
  548. message = _("Current mapset is <%s>.") % mapset,
  549. caption = _("Info"), style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  550. def OnNewVector(self, event):
  551. """!Create new vector map layer"""
  552. dlg = gdialogs.CreateNewVector(self, log = self.goutput,
  553. cmd = (('v.edit',
  554. { 'tool' : 'create' },
  555. 'map')))
  556. if not dlg:
  557. return
  558. name = dlg.GetName(full = True)
  559. if name and dlg.IsChecked('add'):
  560. # add layer to map layer tree
  561. self.curr_page.maptree.AddLayer(ltype = 'vector',
  562. lname = name,
  563. lcmd = ['d.vect', 'map=%s' % name])
  564. dlg.Destroy()
  565. def OnAboutGRASS(self, event):
  566. """!Display 'About GRASS' dialog"""
  567. win = AboutWindow(self)
  568. win.CentreOnScreen()
  569. win.Show(True)
  570. def _popupMenu(self, data):
  571. """!Create popup menu
  572. """
  573. point = wx.GetMousePosition()
  574. menu = wx.Menu()
  575. for key, handler in data:
  576. if key is None:
  577. menu.AppendSeparator()
  578. continue
  579. item = wx.MenuItem(menu, wx.ID_ANY, Icons['layerManager'][key].GetLabel())
  580. item.SetBitmap(Icons['layerManager'][key].GetBitmap(self.iconsize))
  581. menu.AppendItem(item)
  582. self.Bind(wx.EVT_MENU, handler, item)
  583. # create menu
  584. self.PopupMenu(menu)
  585. menu.Destroy()
  586. def OnImportMenu(self, event):
  587. """!Import maps menu (import, link)
  588. """
  589. self._popupMenu((('rastImport', self.OnImportGdalLayers),
  590. ('rastLink', self.OnLinkGdalLayers),
  591. (None, None),
  592. ('vectImport', self.OnImportOgrLayers),
  593. ('vectLink', self.OnLinkOgrLayers)))
  594. def OnWorkspaceNew(self, event = None):
  595. """!Create new workspace file
  596. Erase current workspace settings first
  597. """
  598. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  599. # start new map display if no display is available
  600. if not self.curr_page:
  601. self.NewDisplay()
  602. maptree = self.curr_page.maptree
  603. # ask user to save current settings
  604. if self.workspaceFile and self.workspaceChanged:
  605. self.OnWorkspaceSave()
  606. elif self.workspaceFile is None and maptree.GetCount() > 0:
  607. dlg = wx.MessageDialog(self, message = _("Current workspace is not empty. "
  608. "Do you want to store current settings "
  609. "to workspace file?"),
  610. caption = _("Create new workspace?"),
  611. style = wx.YES_NO | wx.YES_DEFAULT | \
  612. wx.CANCEL | wx.ICON_QUESTION)
  613. ret = dlg.ShowModal()
  614. if ret == wx.ID_YES:
  615. self.OnWorkspaceSaveAs()
  616. elif ret == wx.ID_CANCEL:
  617. dlg.Destroy()
  618. return
  619. dlg.Destroy()
  620. # delete all items
  621. maptree.DeleteAllItems()
  622. # add new root element
  623. maptree.root = maptree.AddRoot("Map Layers")
  624. self.curr_page.maptree.SetPyData(maptree.root, (None,None))
  625. # no workspace file loaded
  626. self.workspaceFile = None
  627. self.workspaceChanged = False
  628. self.SetTitle(self.baseTitle)
  629. def OnWorkspaceOpen(self, event = None):
  630. """!Open file with workspace definition"""
  631. dlg = wx.FileDialog(parent = self, message = _("Choose workspace file"),
  632. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"))
  633. filename = ''
  634. if dlg.ShowModal() == wx.ID_OK:
  635. filename = dlg.GetPath()
  636. if filename == '':
  637. return
  638. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  639. # delete current layer tree content
  640. self.OnWorkspaceClose()
  641. self.LoadWorkspaceFile(filename)
  642. self.workspaceFile = filename
  643. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  644. def LoadWorkspaceFile(self, filename):
  645. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  646. @todo Validate against DTD
  647. @return True on success
  648. @return False on error
  649. """
  650. # dtd
  651. dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  652. # parse workspace file
  653. try:
  654. gxwXml = workspace.ProcessWorkspaceFile(etree.parse(filename))
  655. except Exception, e:
  656. gcmd.GError(parent = self,
  657. message = _("Reading workspace file <%s> failed.\n"
  658. "Invalid file, unable to parse XML document.") % filename)
  659. return
  660. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  661. parent = self)
  662. wx.Yield()
  663. #
  664. # load layer manager window properties
  665. #
  666. if UserSettings.Get(group = 'workspace', key = 'posManager', subkey = 'enabled') is False:
  667. if gxwXml.layerManager['pos']:
  668. self.SetPosition(gxwXml.layerManager['pos'])
  669. if gxwXml.layerManager['size']:
  670. self.SetSize(gxwXml.layerManager['size'])
  671. #
  672. # start map displays first (list of layers can be empty)
  673. #
  674. displayId = 0
  675. mapdisplay = list()
  676. for display in gxwXml.displays:
  677. mapdisp = self.NewDisplay(show = False)
  678. mapdisplay.append(mapdisp)
  679. maptree = self.gm_cb.GetPage(displayId).maptree
  680. # set windows properties
  681. mapdisp.SetProperties(render = display['render'],
  682. mode = display['mode'],
  683. showCompExtent = display['showCompExtent'],
  684. alignExtent = display['alignExtent'],
  685. constrainRes = display['constrainRes'],
  686. projection = display['projection']['enabled'])
  687. if display['projection']['enabled']:
  688. if display['projection']['epsg']:
  689. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  690. value = display['projection']['epsg'])
  691. if display['projection']['proj']:
  692. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  693. value = display['projection']['proj'])
  694. # set position and size of map display
  695. if UserSettings.Get(group = 'workspace', key = 'posDisplay', subkey = 'enabled') is False:
  696. if display['pos']:
  697. mapdisp.SetPosition(display['pos'])
  698. if display['size']:
  699. mapdisp.SetSize(display['size'])
  700. # set extent if defined
  701. if display['extent']:
  702. w, s, e, n = display['extent']
  703. region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
  704. mapdisp.GetWindow().ResetZoomHistory()
  705. mapdisp.GetWindow().ZoomHistory(region['n'],
  706. region['s'],
  707. region['e'],
  708. region['w'])
  709. mapdisp.Show()
  710. displayId += 1
  711. maptree = None
  712. selected = [] # list of selected layers
  713. #
  714. # load list of map layers
  715. #
  716. for layer in gxwXml.layers:
  717. display = layer['display']
  718. maptree = self.gm_cb.GetPage(display).maptree
  719. newItem = maptree.AddLayer(ltype = layer['type'],
  720. lname = layer['name'],
  721. lchecked = layer['checked'],
  722. lopacity = layer['opacity'],
  723. lcmd = layer['cmd'],
  724. lgroup = layer['group'],
  725. lnviz = layer['nviz'],
  726. lvdigit = layer['vdigit'])
  727. if layer.has_key('selected'):
  728. if layer['selected']:
  729. selected.append((maptree, newItem))
  730. else:
  731. maptree.SelectItem(newItem, select = False)
  732. for maptree, layer in selected:
  733. if not maptree.IsSelected(layer):
  734. maptree.SelectItem(layer, select = True)
  735. maptree.layer_selected = layer
  736. busy.Destroy()
  737. if maptree:
  738. # reverse list of map layers
  739. maptree.Map.ReverseListOfLayers()
  740. for idx, mdisp in enumerate(mapdisplay):
  741. mdisp.MapWindow2D.UpdateMap()
  742. #nviz
  743. if gxwXml.displays[idx]['viewMode'] == '3d':
  744. mdisp.AddNviz()
  745. self.nviz.UpdateState(view = gxwXml.nviz_state['view'],
  746. iview = gxwXml.nviz_state['iview'],
  747. light = gxwXml.nviz_state['light'])
  748. mdisp.MapWindow3D.constants = gxwXml.nviz_state['constants']
  749. for idx, constant in enumerate(mdisp.MapWindow3D.constants):
  750. mdisp.MapWindow3D.AddConstant(constant, idx + 1)
  751. for page in ('view', 'light', 'fringe', 'constant', 'cplane'):
  752. self.nviz.UpdatePage(page)
  753. self.nviz.UpdateSettings()
  754. mapdisp.toolbars['map'].combo.SetSelection(1)
  755. return True
  756. def OnWorkspaceLoadGrcFile(self, event):
  757. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  758. dlg = wx.FileDialog(parent = self, message = _("Choose GRC file to load"),
  759. defaultDir = os.getcwd(), wildcard = _("Old GRASS Workspace File (*.grc)|*.grc"))
  760. filename = ''
  761. if dlg.ShowModal() == wx.ID_OK:
  762. filename = dlg.GetPath()
  763. if filename == '':
  764. return
  765. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  766. # start new map display if no display is available
  767. if not self.curr_page:
  768. self.NewDisplay()
  769. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  770. parent = self)
  771. wx.Yield()
  772. maptree = None
  773. for layer in workspace.ProcessGrcFile(filename).read(self):
  774. maptree = self.gm_cb.GetPage(layer['display']).maptree
  775. newItem = maptree.AddLayer(ltype = layer['type'],
  776. lname = layer['name'],
  777. lchecked = layer['checked'],
  778. lopacity = layer['opacity'],
  779. lcmd = layer['cmd'],
  780. lgroup = layer['group'])
  781. busy.Destroy()
  782. if maptree:
  783. # reverse list of map layers
  784. maptree.Map.ReverseListOfLayers()
  785. def OnWorkspaceSaveAs(self, event = None):
  786. """!Save workspace definition to selected file"""
  787. dlg = wx.FileDialog(parent = self, message = _("Choose file to save current workspace"),
  788. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
  789. filename = ''
  790. if dlg.ShowModal() == wx.ID_OK:
  791. filename = dlg.GetPath()
  792. if filename == '':
  793. return False
  794. # check for extension
  795. if filename[-4:] != ".gxw":
  796. filename += ".gxw"
  797. if os.path.exists(filename):
  798. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  799. "Do you want to overwrite this file?") % filename,
  800. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  801. if dlg.ShowModal() != wx.ID_YES:
  802. dlg.Destroy()
  803. return False
  804. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  805. self.SaveToWorkspaceFile(filename)
  806. self.workspaceFile = filename
  807. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  808. def OnWorkspaceSave(self, event = None):
  809. """!Save file with workspace definition"""
  810. if self.workspaceFile:
  811. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  812. "Do you want to overwrite this file?") % \
  813. self.workspaceFile,
  814. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  815. if dlg.ShowModal() == wx.ID_NO:
  816. dlg.Destroy()
  817. else:
  818. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  819. self.SaveToWorkspaceFile(self.workspaceFile)
  820. self.SetTitle(self.baseTitle + " - " + os.path.basename(self.workspaceFile))
  821. self.workspaceChanged = False
  822. else:
  823. self.OnWorkspaceSaveAs()
  824. def SaveToWorkspaceFile(self, filename):
  825. """!Save layer tree layout to workspace file
  826. Return True on success, False on error
  827. """
  828. tmpfile = tempfile.TemporaryFile(mode = 'w+b')
  829. try:
  830. workspace.WriteWorkspaceFile(lmgr = self, file = tmpfile)
  831. except StandardError, e:
  832. gcmd.GError(parent = self,
  833. message = _("Writing current settings to workspace file "
  834. "failed."))
  835. return False
  836. try:
  837. mfile = open(filename, "w")
  838. tmpfile.seek(0)
  839. for line in tmpfile.readlines():
  840. mfile.write(line)
  841. except IOError:
  842. gcmd.GError(parent = self,
  843. message = _("Unable to open file <%s> for writing.") % filename)
  844. return False
  845. mfile.close()
  846. return True
  847. def OnWorkspaceClose(self, event = None):
  848. """!Close file with workspace definition
  849. If workspace has been modified ask user to save the changes.
  850. """
  851. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  852. self.OnDisplayCloseAll()
  853. self.workspaceFile = None
  854. self.workspaceChanged = False
  855. self.SetTitle(self.baseTitle)
  856. self.disp_idx = 0
  857. self.curr_page = None
  858. def OnDisplayClose(self, event = None):
  859. """!Close current map display window
  860. """
  861. if self.curr_page and self.curr_page.maptree.mapdisplay:
  862. self.curr_page.maptree.mapdisplay.OnCloseWindow(event)
  863. def OnDisplayCloseAll(self, event = None):
  864. """!Close all open map display windows
  865. """
  866. displays = list()
  867. for page in range(0, self.gm_cb.GetPageCount()):
  868. displays.append(self.gm_cb.GetPage(page).maptree.mapdisplay)
  869. for display in displays:
  870. display.OnCloseWindow(event)
  871. def RulesCmd(self, event):
  872. """!Launches dialog for commands that need rules input and
  873. processes rules
  874. """
  875. cmd = self.GetMenuCmd(event)
  876. if cmd[0] == 'r.colors':
  877. ctable = colorrules.RasterColorTable(self)
  878. else:
  879. ctable = colorrules.VectorColorTable(self, attributeType = 'color')
  880. ctable.CentreOnScreen()
  881. ctable.Show()
  882. def OnInstallExtension(self, event):
  883. """!Install extension from GRASS Addons SVN repository"""
  884. win = InstallExtensionWindow(self, size = (650, 550))
  885. win.CentreOnScreen()
  886. win.Show()
  887. def OnPreferences(self, event):
  888. """!General GUI preferences/settings
  889. """
  890. if not self.dialogs['preferences']:
  891. dlg = preferences.PreferencesDialog(parent = self)
  892. self.dialogs['preferences'] = dlg
  893. self.dialogs['preferences'].CenterOnScreen()
  894. dlg.Bind(preferences.EVT_SETTINGS_CHANGED, self.OnSettingsChanged)
  895. self.dialogs['preferences'].ShowModal()
  896. def OnHelp(self, event):
  897. """!Show help
  898. """
  899. self.goutput.RunCmd(['g.manual','-i'])
  900. def DispHistogram(self, event):
  901. """
  902. Init histogram display canvas and tools
  903. """
  904. self.histogram = histogram.HistFrame(self,
  905. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  906. style = wx.DEFAULT_FRAME_STYLE)
  907. #show new display
  908. self.histogram.Show()
  909. self.histogram.Refresh()
  910. self.histogram.Update()
  911. def DispProfile(self, event):
  912. """
  913. Init profile canvas and tools
  914. """
  915. self.profile = profile.ProfileFrame(self,
  916. id = wx.ID_ANY, pos = wx.DefaultPosition, size = (400,300),
  917. style = wx.DEFAULT_FRAME_STYLE)
  918. self.profile.Show()
  919. self.profile.Refresh()
  920. self.profile.Update()
  921. def OnMapCalculator(self, event, cmd = ''):
  922. """!Init map calculator for interactive creation of mapcalc statements
  923. """
  924. if event:
  925. try:
  926. cmd = self.GetMenuCmd(event)
  927. except KeyError:
  928. cmd = ['r.mapcalc']
  929. win = mapcalculator.MapCalcFrame(parent = self,
  930. cmd = cmd[0])
  931. win.CentreOnScreen()
  932. win.Show()
  933. def OnVectorCleaning(self, event, cmd = ''):
  934. """!Init interactive vector cleaning
  935. """
  936. if event:
  937. cmd = self.GetMenuCmd(event)
  938. win = vclean.VectorCleaningFrame(parent = self, cmd = cmd[0])
  939. win.CentreOnScreen()
  940. win.Show()
  941. def OnImportDxfFile(self, event, cmd = None):
  942. """!Convert multiple DXF layers to GRASS vector map layers"""
  943. dlg = gdialogs.DxfImportDialog(parent = self)
  944. dlg.CentreOnScreen()
  945. dlg.Show()
  946. def OnImportGdalLayers(self, event, cmd = None):
  947. """!Convert multiple GDAL layers to GRASS raster map layers"""
  948. dlg = gdialogs.GdalImportDialog(parent = self)
  949. dlg.CentreOnScreen()
  950. dlg.Show()
  951. def OnLinkGdalLayers(self, event, cmd = None):
  952. """!Link multiple GDAL layers to GRASS raster map layers"""
  953. dlg = gdialogs.GdalImportDialog(parent = self, link = True)
  954. dlg.CentreOnScreen()
  955. dlg.Show()
  956. def OnImportOgrLayers(self, event, cmd = None):
  957. """!Convert multiple OGR layers to GRASS vector map layers"""
  958. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True)
  959. dlg.CentreOnScreen()
  960. dlg.Show()
  961. def OnLinkOgrLayers(self, event, cmd = None):
  962. """!Links multiple OGR layers to GRASS vector map layers"""
  963. dlg = gdialogs.GdalImportDialog(parent = self, ogr = True, link = True)
  964. dlg.CentreOnScreen()
  965. dlg.Show()
  966. def OnImportWMS(self, event):
  967. """!Import data from OGC WMS server"""
  968. dlg = ogc_services.WMSDialog(parent = self, service = 'wms')
  969. dlg.CenterOnScreen()
  970. if dlg.ShowModal() == wx.ID_OK: # -> import layers
  971. layers = dlg.GetLayers()
  972. if len(layers.keys()) > 0:
  973. for layer in layers.keys():
  974. cmd = ['r.in.wms',
  975. 'mapserver=%s' % dlg.GetSettings()['server'],
  976. 'layers=%s' % layer,
  977. 'output=%s' % layer,
  978. 'format=png',
  979. '--overwrite']
  980. styles = ','.join(layers[layer])
  981. if styles:
  982. cmd.append('styles=%s' % styles)
  983. self.goutput.RunCmd(cmd, switchPage = True)
  984. self.curr_page.maptree.AddLayer(ltype = 'raster',
  985. lname = layer,
  986. lcmd = ['d.rast', 'map=%s' % layer],
  987. multiple = False)
  988. else:
  989. self.goutput.WriteWarning(_("Nothing to import. No WMS layer selected."))
  990. dlg.Destroy()
  991. def OnShowAttributeTable(self, event, selection = None):
  992. """!Show attribute table of the given vector map layer
  993. """
  994. if not self.curr_page:
  995. self.MsgNoLayerSelected()
  996. return
  997. tree = self.GetLayerTree()
  998. layer = tree.layer_selected
  999. # no map layer selected
  1000. if not layer:
  1001. self.MsgNoLayerSelected()
  1002. return
  1003. # available only for vector map layers
  1004. try:
  1005. maptype = tree.GetPyData(layer)[0]['maplayer'].type
  1006. except:
  1007. maptype = None
  1008. if not maptype or maptype != 'vector':
  1009. gcmd.GMessage(parent = self,
  1010. message = _("Selected map layer is not vector."))
  1011. return
  1012. if not tree.GetPyData(layer)[0]:
  1013. return
  1014. dcmd = tree.GetPyData(layer)[0]['cmd']
  1015. if not dcmd:
  1016. return
  1017. busy = wx.BusyInfo(message = _("Please wait, loading attribute data..."),
  1018. parent = self)
  1019. wx.Yield()
  1020. dbmanager = dbm.AttributeManager(parent = self, id = wx.ID_ANY,
  1021. size = wx.Size(500, 300),
  1022. item = layer, log = self.goutput,
  1023. selection = selection)
  1024. busy.Destroy()
  1025. # register ATM dialog
  1026. self.dialogs['atm'].append(dbmanager)
  1027. # show ATM window
  1028. dbmanager.Show()
  1029. def OnNewDisplayWMS(self, event = None):
  1030. """!Create new layer tree and map display instance"""
  1031. self.NewDisplayWMS()
  1032. def NewDisplayWMS(self, show = True):
  1033. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  1034. try:
  1035. from gui_modules.wms.wmsmenu import DisplayWMSMenu
  1036. except:
  1037. gcmd.GError(parent = self.parent,
  1038. message = _("Experimental WMS support for wxGUI not available. "
  1039. "You can install it by '%s'") % \
  1040. "g.extension -s extension=wx.wms")
  1041. return
  1042. DisplayWMSMenu()
  1043. def OnNewDisplay(self, event = None):
  1044. """!Create new layer tree and map display instance"""
  1045. self.NewDisplay()
  1046. def NewDisplay(self, show = True):
  1047. """!Create new layer tree, which will
  1048. create an associated map display frame
  1049. @param show show map display window if True
  1050. @return reference to mapdisplay intance
  1051. """
  1052. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.disp_idx)
  1053. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  1054. self.pg_panel = wx.Panel(self.gm_cb, id = wx.ID_ANY, style = wx.EXPAND)
  1055. self.gm_cb.AddPage(self.pg_panel, text = "Display "+ str(self.disp_idx + 1), select = True)
  1056. self.curr_page = self.gm_cb.GetCurrentPage()
  1057. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  1058. self.curr_page.maptree = layertree.LayerTree(self.curr_page, id = wx.ID_ANY, pos = wx.DefaultPosition,
  1059. size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
  1060. wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
  1061. wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
  1062. idx = self.disp_idx, lmgr = self, notebook = self.gm_cb,
  1063. auimgr = self._auimgr, showMapDisplay = show)
  1064. # layout for controls
  1065. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  1066. cb_boxsizer.Add(self.curr_page.maptree, proportion = 1, flag = wx.EXPAND, border = 1)
  1067. self.curr_page.SetSizer(cb_boxsizer)
  1068. cb_boxsizer.Fit(self.curr_page.maptree)
  1069. self.curr_page.Layout()
  1070. self.curr_page.maptree.Layout()
  1071. # use default window layout
  1072. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  1073. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  1074. idx = 4 + self.disp_idx * 4
  1075. try:
  1076. x, y = map(int, dim.split(',')[idx:idx + 2])
  1077. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  1078. self.curr_page.maptree.mapdisplay.SetPosition((x, y))
  1079. self.curr_page.maptree.mapdisplay.SetSize((w, h))
  1080. except:
  1081. pass
  1082. self.disp_idx += 1
  1083. return self.curr_page.maptree.mapdisplay
  1084. def OnAddMaps(self, event = None):
  1085. """!Add selected map layers into layer tree"""
  1086. dialog = gdialogs.AddMapLayersDialog(parent = self, title = _("Add selected map layers into layer tree"))
  1087. if dialog.ShowModal() == wx.ID_OK:
  1088. # start new map display if no display is available
  1089. if not self.curr_page:
  1090. self.NewDisplay()
  1091. maptree = self.curr_page.maptree
  1092. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  1093. parent = self)
  1094. wx.Yield()
  1095. for layerName in dialog.GetMapLayers():
  1096. if dialog.GetLayerType() == 'raster':
  1097. cmd = ['d.rast', 'map=%s' % layerName]
  1098. elif dialog.GetLayerType() == 'vector':
  1099. cmd = ['d.vect', 'map=%s' % layerName]
  1100. newItem = maptree.AddLayer(ltype = dialog.GetLayerType(),
  1101. lname = layerName,
  1102. lchecked = False,
  1103. lopacity = 1.0,
  1104. lcmd = cmd,
  1105. lgroup = None)
  1106. busy.Destroy()
  1107. def OnAddRaster(self, event):
  1108. """!Add raster map layer"""
  1109. # start new map display if no display is available
  1110. if not self.curr_page:
  1111. self.NewDisplay(show = True)
  1112. self.notebook.SetSelectionByName('layers')
  1113. self.curr_page.maptree.AddLayer('raster')
  1114. def OnAddRaster3D(self, event):
  1115. """!Add 3D raster map layer"""
  1116. # start new map display if no display is available
  1117. if not self.curr_page:
  1118. self.NewDisplay(show = True)
  1119. self.AddRaster3D(event)
  1120. def OnAddRasterMisc(self, event):
  1121. """!Create misc raster popup-menu"""
  1122. # start new map display if no display is available
  1123. if not self.curr_page:
  1124. self.NewDisplay(show = True)
  1125. self._popupMenu((('addRast3d', self.OnAddRaster3D),
  1126. (None, None),
  1127. ('addRgb', self.OnAddRasterRGB),
  1128. ('addHis', self.OnAddRasterHIS),
  1129. (None, None),
  1130. ('addShaded', self.OnAddRasterShaded),
  1131. (None, None),
  1132. ('addRArrow', self.OnAddRasterArrow),
  1133. ('addRNum', self.OnAddRasterNum)))
  1134. # show map display
  1135. self.curr_page.maptree.mapdisplay.Show()
  1136. def OnAddVector(self, event):
  1137. """!Add vector map to the current layer tree"""
  1138. # start new map display if no display is available
  1139. if not self.curr_page:
  1140. self.NewDisplay(show = True)
  1141. self.notebook.SetSelectionByName('layers')
  1142. self.curr_page.maptree.AddLayer('vector')
  1143. def OnAddVectorMisc(self, event):
  1144. """!Create misc vector popup-menu"""
  1145. # start new map display if no display is available
  1146. if not self.curr_page:
  1147. self.NewDisplay(show = True)
  1148. self._popupMenu((('addThematic', self.OnAddVectorTheme),
  1149. ('addChart', self.OnAddVectorChart)))
  1150. # show map display
  1151. self.curr_page.maptree.mapdisplay.Show()
  1152. def OnAddVectorTheme(self, event):
  1153. """!Add thematic vector map to the current layer tree"""
  1154. self.notebook.SetSelectionByName('layers')
  1155. self.curr_page.maptree.AddLayer('thememap')
  1156. def OnAddVectorChart(self, event):
  1157. """!Add chart vector map to the current layer tree"""
  1158. self.notebook.SetSelectionByName('layers')
  1159. self.curr_page.maptree.AddLayer('themechart')
  1160. def OnAddOverlay(self, event):
  1161. """!Create decoration overlay menu"""
  1162. # start new map display if no display is available
  1163. if not self.curr_page:
  1164. self.NewDisplay(show = True)
  1165. self._popupMenu((('addGrid', self.OnAddGrid),
  1166. ('addLabels', self.OnAddLabels),
  1167. ('addGeodesic', self.OnAddGeodesic),
  1168. ('addRhumb', self.OnAddRhumb),
  1169. (None, None),
  1170. ('addCmd', self.OnAddCommand)))
  1171. # show map display
  1172. self.curr_page.maptree.mapdisplay.Show()
  1173. def OnAddRaster3D(self, event):
  1174. """!Add 3D raster map to the current layer tree"""
  1175. self.notebook.SetSelectionByName('layers')
  1176. self.curr_page.maptree.AddLayer('3d-raster')
  1177. def OnAddRasterRGB(self, event):
  1178. """!Add RGB raster map to the current layer tree"""
  1179. self.notebook.SetSelectionByName('layers')
  1180. self.curr_page.maptree.AddLayer('rgb')
  1181. def OnAddRasterHIS(self, event):
  1182. """!Add HIS raster map to the current layer tree"""
  1183. self.notebook.SetSelectionByName('layers')
  1184. self.curr_page.maptree.AddLayer('his')
  1185. def OnAddRasterShaded(self, event):
  1186. """!Add shaded relief raster map to the current layer tree"""
  1187. self.notebook.SetSelectionByName('layers')
  1188. self.curr_page.maptree.AddLayer('shaded')
  1189. def OnAddRasterArrow(self, event):
  1190. """!Add flow arrows raster map to the current layer tree"""
  1191. self.notebook.SetSelectionByName('layers')
  1192. self.curr_page.maptree.AddLayer('rastarrow')
  1193. def OnAddRasterNum(self, event):
  1194. """!Add cell number raster map to the current layer tree"""
  1195. self.notebook.SetSelectionByName('layers')
  1196. self.curr_page.maptree.AddLayer('rastnum')
  1197. def OnAddCommand(self, event):
  1198. """!Add command line map layer to the current layer tree"""
  1199. # start new map display if no display is available
  1200. if not self.curr_page:
  1201. self.NewDisplay(show = True)
  1202. self.notebook.SetSelectionByName('layers')
  1203. self.curr_page.maptree.AddLayer('command')
  1204. # show map display
  1205. self.curr_page.maptree.mapdisplay.Show()
  1206. def OnAddGroup(self, event):
  1207. """!Add layer group"""
  1208. # start new map display if no display is available
  1209. if not self.curr_page:
  1210. self.NewDisplay(show = True)
  1211. self.notebook.SetSelectionByName('layers')
  1212. self.curr_page.maptree.AddLayer('group')
  1213. # show map display
  1214. self.curr_page.maptree.mapdisplay.Show()
  1215. def OnAddGrid(self, event):
  1216. """!Add grid map layer to the current layer tree"""
  1217. self.notebook.SetSelectionByName('layers')
  1218. self.curr_page.maptree.AddLayer('grid')
  1219. def OnAddGeodesic(self, event):
  1220. """!Add geodesic line map layer to the current layer tree"""
  1221. self.notebook.SetSelectionByName('layers')
  1222. self.curr_page.maptree.AddLayer('geodesic')
  1223. def OnAddRhumb(self, event):
  1224. """!Add rhumb map layer to the current layer tree"""
  1225. self.notebook.SetSelectionByName('layers')
  1226. self.curr_page.maptree.AddLayer('rhumb')
  1227. def OnAddLabels(self, event):
  1228. """!Add vector labels map layer to the current layer tree"""
  1229. # start new map display if no display is available
  1230. if not self.curr_page:
  1231. self.NewDisplay(show = True)
  1232. self.notebook.SetSelectionByName('layers')
  1233. self.curr_page.maptree.AddLayer('labels')
  1234. # show map display
  1235. self.curr_page.maptree.mapdisplay.Show()
  1236. def OnDeleteLayer(self, event):
  1237. """!Remove selected map layer from the current layer Tree
  1238. """
  1239. if not self.curr_page or not self.curr_page.maptree.layer_selected:
  1240. self.MsgNoLayerSelected()
  1241. return
  1242. if UserSettings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'):
  1243. layerName = ''
  1244. for item in self.curr_page.maptree.GetSelections():
  1245. name = str(self.curr_page.maptree.GetItemText(item))
  1246. idx = name.find('(opacity')
  1247. if idx > -1:
  1248. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1249. else:
  1250. layerName += '<' + name + '>,\n'
  1251. layerName = layerName.rstrip(',\n')
  1252. if len(layerName) > 2: # <>
  1253. message = _("Do you want to remove map layer(s)\n%s\n"
  1254. "from layer tree?") % layerName
  1255. else:
  1256. message = _("Do you want to remove selected map layer(s) "
  1257. "from layer tree?")
  1258. dlg = wx.MessageDialog (parent = self, message = message,
  1259. caption = _("Remove map layer"),
  1260. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1261. if dlg.ShowModal() != wx.ID_YES:
  1262. dlg.Destroy()
  1263. return
  1264. dlg.Destroy()
  1265. for layer in self.curr_page.maptree.GetSelections():
  1266. if self.curr_page.maptree.GetPyData(layer)[0]['type'] == 'group':
  1267. self.curr_page.maptree.DeleteChildren(layer)
  1268. self.curr_page.maptree.Delete(layer)
  1269. def OnKeyDown(self, event):
  1270. """!Key pressed"""
  1271. kc = event.GetKeyCode()
  1272. if event.ControlDown():
  1273. if kc == wx.WXK_TAB:
  1274. # switch layer list / command output
  1275. if self.notebook.GetSelection() == self.notebook.GetPageIndexByName('layers'):
  1276. self.notebook.SetSelectionByName('output')
  1277. else:
  1278. self.notebook.SetSelectionByName('layers')
  1279. try:
  1280. ckc = chr(kc)
  1281. except ValueError:
  1282. event.Skip()
  1283. return
  1284. if event.CtrlDown():
  1285. if kc == 'R':
  1286. self.OnAddRaster(None)
  1287. elif kc == 'V':
  1288. self.OnAddVector(None)
  1289. event.Skip()
  1290. def OnCloseWindow(self, event):
  1291. """!Cleanup when wxGUI is quitted"""
  1292. if not self.curr_page:
  1293. self._auimgr.UnInit()
  1294. self.Destroy()
  1295. return
  1296. maptree = self.curr_page.maptree
  1297. if self.workspaceChanged and \
  1298. UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  1299. if self.workspaceFile:
  1300. message = _("Do you want to save changes in the workspace?")
  1301. else:
  1302. message = _("Do you want to store current settings "
  1303. "to workspace file?")
  1304. # ask user to save current settings
  1305. if maptree.GetCount() > 0:
  1306. dlg = wx.MessageDialog(self,
  1307. message = message,
  1308. caption = _("Quit GRASS GUI"),
  1309. style = wx.YES_NO | wx.YES_DEFAULT |
  1310. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1311. ret = dlg.ShowModal()
  1312. if ret == wx.ID_YES:
  1313. if not self.workspaceFile:
  1314. self.OnWorkspaceSaveAs()
  1315. else:
  1316. self.SaveToWorkspaceFile(self.workspaceFile)
  1317. elif ret == wx.ID_CANCEL:
  1318. event.Veto()
  1319. dlg.Destroy()
  1320. return
  1321. dlg.Destroy()
  1322. # don't ask any more...
  1323. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1324. value = False)
  1325. self.OnDisplayCloseAll()
  1326. self.gm_cb.DeleteAllPages()
  1327. self._auimgr.UnInit()
  1328. self.Destroy()
  1329. def MsgNoLayerSelected(self):
  1330. """!Show dialog message 'No layer selected'"""
  1331. wx.MessageBox(parent = self,
  1332. message = _("No map layer selected. Operation cancelled."),
  1333. caption = _("Message"),
  1334. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1335. class GMApp(wx.App):
  1336. def __init__(self, workspace = None):
  1337. """!Main GUI class.
  1338. @param workspace path to the workspace file
  1339. """
  1340. self.workspaceFile = workspace
  1341. # call parent class initializer
  1342. wx.App.__init__(self, False)
  1343. self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
  1344. def OnInit(self):
  1345. """!Initialize all available image handlers
  1346. @return True
  1347. """
  1348. wx.InitAllImageHandlers()
  1349. # create splash screen
  1350. introImagePath = os.path.join(globalvar.ETCIMGDIR, "silesia_splash.png")
  1351. introImage = wx.Image(introImagePath, wx.BITMAP_TYPE_PNG)
  1352. introBmp = introImage.ConvertToBitmap()
  1353. if SC:
  1354. splash = SC.AdvancedSplash(bitmap = introBmp,
  1355. timeout = 2000, parent = None, id = wx.ID_ANY)
  1356. splash.SetText(_('Starting GRASS GUI...'))
  1357. splash.SetTextColour(wx.Colour(45, 52, 27))
  1358. splash.SetTextFont(wx.Font(pointSize = 15, family = wx.DEFAULT, style = wx.NORMAL,
  1359. weight = wx.BOLD))
  1360. splash.SetTextPosition((150, 430))
  1361. else:
  1362. wx.SplashScreen (bitmap = introBmp, splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT,
  1363. milliseconds = 2000, parent = None, id = wx.ID_ANY)
  1364. wx.Yield()
  1365. ### TODO: adjust initial window layout if necessary
  1366. w, h = wx.GetDisplaySize()
  1367. # only neccessary if one of the windows is falling out of
  1368. # the current display size
  1369. # check if settings file exists
  1370. # if settings file exists, check if we should use the stored settings
  1371. # if we should use stored settings, use stored settings
  1372. # else use default settings
  1373. # else if settings file does not exist, use default settings
  1374. # check if any of the windows is falling out of the current display
  1375. # if yes, pull it in
  1376. # falling out to the right
  1377. # x pos = display width - window width
  1378. # falling out to the bottom
  1379. # y pos = 0
  1380. # update settings
  1381. # if settings file exists, update settings but keep settings for
  1382. # additional map display windows, or update them too
  1383. # do not erase settings for additional map display windows !
  1384. # create and show main frame
  1385. mainframe = GMFrame(parent = None, id = wx.ID_ANY,
  1386. workspace = self.workspaceFile)
  1387. mainframe.Show()
  1388. self.SetTopWindow(mainframe)
  1389. return True
  1390. class Usage(Exception):
  1391. def __init__(self, msg):
  1392. self.msg = msg
  1393. def printHelp():
  1394. """!Print program help"""
  1395. print >> sys.stderr, "Usage:"
  1396. print >> sys.stderr, " python wxgui.py [options]"
  1397. print >> sys.stderr, "%sOptions:" % os.linesep
  1398. print >> sys.stderr, " -w\t--workspace file\tWorkspace file to load"
  1399. sys.exit(0)
  1400. def process_opt(opts, args):
  1401. """!Process command-line arguments"""
  1402. workspaceFile = None
  1403. for o, a in opts:
  1404. if o in ("-h", "--help"):
  1405. printHelp()
  1406. if o in ("-w", "--workspace"):
  1407. if a != '':
  1408. workspaceFile = str(a)
  1409. else:
  1410. workspaceFile = args.pop(0)
  1411. return (workspaceFile,)
  1412. def main(argv = None):
  1413. import gettext
  1414. gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  1415. if argv is None:
  1416. argv = sys.argv
  1417. try:
  1418. try:
  1419. opts, args = getopt.getopt(argv[1:], "hw:",
  1420. ["help", "workspace"])
  1421. except getopt.error, msg:
  1422. raise Usage(msg)
  1423. except Usage, err:
  1424. print >> sys.stderr, err.msg
  1425. print >> sys.stderr, "for help use --help"
  1426. printHelp()
  1427. workspaceFile = process_opt(opts, args)[0]
  1428. app = GMApp(workspaceFile)
  1429. # suppress wxPython logs
  1430. q = wx.LogNull()
  1431. app.MainLoop()
  1432. if __name__ == "__main__":
  1433. sys.exit(main())