frame.py 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117
  1. # -*- coding: utf-8 -*-
  2. """!
  3. @package lmgr::frame
  4. @brief Layer Manager - main menu, layer management toolbar, notebook
  5. control for display management and access to command console.
  6. Classes:
  7. - frame::GMFrame
  8. (C) 2006-2013 by the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Michael Barton (Arizona State University)
  12. @author Jachym Cepicky (Mendel University of Agriculture)
  13. @author Martin Landa <landa.martin gmail.com>
  14. @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
  15. """
  16. import sys
  17. import os
  18. import tempfile
  19. import stat
  20. import platform
  21. import re
  22. try:
  23. import xml.etree.ElementTree as etree
  24. except ImportError:
  25. import elementtree.ElementTree as etree # Python <= 2.4
  26. from core import globalvar
  27. import wx
  28. import wx.aui
  29. try:
  30. import wx.lib.agw.flatnotebook as FN
  31. except ImportError:
  32. import wx.lib.flatnotebook as FN
  33. if os.path.join(globalvar.ETCDIR, "python") not in sys.path:
  34. sys.path.append(os.path.join(globalvar.ETCDIR, "python"))
  35. from grass.script import core as grass
  36. from core.gcmd import RunCommand, GError, GMessage, GException
  37. from core.settings import UserSettings, GetDisplayVectSettings
  38. from core.utils import SetAddOnPath, GetLayerNameFromCmd, command2ltype, _
  39. from gui_core.preferences import MapsetAccess, PreferencesDialog
  40. from lmgr.layertree import LayerTree, LMIcons
  41. from lmgr.menudata import LayerManagerMenuData, LayerManagerModuleTree
  42. from gui_core.widgets import GNotebook
  43. from modules.mcalc_builder import MapCalcFrame
  44. from dbmgr.manager import AttributeManager
  45. from core.workspace import ProcessWorkspaceFile, ProcessGrcFile, WriteWorkspaceFile
  46. from core.gconsole import GConsole, EVT_IGNORED_CMD_RUN
  47. from core.giface import Notification
  48. from gui_core.goutput import GConsoleWindow, GC_SEARCH, GC_PROMPT
  49. from gui_core.dialogs import GdalOutputDialog, DxfImportDialog, GdalImportDialog, MapLayersDialog
  50. from gui_core.dialogs import LocationDialog, MapsetDialog, CreateNewVector, GroupDialog
  51. from modules.colorrules import RasterColorTable, VectorColorTable
  52. from gui_core.menu import Menu, SearchModuleWindow
  53. from gmodeler.model import Model
  54. from gmodeler.frame import ModelFrame
  55. from psmap.frame import PsMapFrame
  56. from core.debug import Debug
  57. from gui_core.ghelp import AboutWindow
  58. from modules.extensions import InstallExtensionWindow, ManageExtensionWindow
  59. from lmgr.toolbars import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar
  60. from lmgr.toolbars import LMMiscToolbar, LMVectorToolbar, LMNvizToolbar
  61. from lmgr.pyshell import PyShellWindow
  62. from lmgr.giface import LayerManagerGrassInterface
  63. from gui_core.forms import GUI
  64. from gcp.manager import GCPWizard
  65. from nviz.main import haveNviz
  66. from nviz.preferences import NvizPreferencesDialog
  67. from mapswipe.frame import SwipeMapFrame
  68. from rlisetup.frame import RLiSetupFrame
  69. class GMFrame(wx.Frame):
  70. """!Layer Manager frame with notebook widget for controlling GRASS
  71. GIS. Includes command console page for typing GRASS (and other)
  72. commands, tree widget page for managing map layers.
  73. """
  74. def __init__(self, parent, id = wx.ID_ANY, title = _("GRASS GIS Layer Manager"),
  75. workspace = None,
  76. size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
  77. self.parent = parent
  78. self.baseTitle = title
  79. self.iconsize = (16, 16)
  80. self.displayIndex = 0 # index value for map displays and layer trees
  81. self.currentPage = None # currently selected page for layer tree notebook
  82. self.currentPageNum = None # currently selected page number for layer tree notebook
  83. self.workspaceFile = workspace # workspace file
  84. self.workspaceChanged = False # track changes in workspace
  85. self.cwdPath = None # current working directory
  86. wx.Frame.__init__(self, parent = parent, id = id, size = size,
  87. style = style, **kwargs)
  88. self._setTitle()
  89. self.SetName("LayerManager")
  90. self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
  91. self._giface = LayerManagerGrassInterface(self)
  92. # the main menu bar
  93. self._menuTreeBuilder = LayerManagerMenuData()
  94. # the search tree and command console
  95. self._moduleTreeBuilder = LayerManagerModuleTree()
  96. self._auimgr = wx.aui.AuiManager(self)
  97. # list of open dialogs
  98. self.dialogs = dict()
  99. self.dialogs['preferences'] = None
  100. self.dialogs['nvizPreferences'] = None
  101. self.dialogs['atm'] = list()
  102. # create widgets
  103. self._createMenuBar()
  104. self.statusbar = self.CreateStatusBar(number = 1)
  105. self.notebook = self._createNoteBook()
  106. self.toolbars = { 'workspace' : LMWorkspaceToolbar(parent = self),
  107. 'data' : LMDataToolbar(parent = self),
  108. 'tools' : LMToolsToolbar(parent = self),
  109. 'misc' : LMMiscToolbar(parent = self),
  110. 'vector' : LMVectorToolbar(parent = self),
  111. 'nviz' : LMNvizToolbar(parent = self)}
  112. self._toolbarsData = { 'workspace' : ("toolbarWorkspace", # name
  113. _("Workspace Toolbar"), # caption
  114. 1), # row
  115. 'data' : ("toolbarData",
  116. _("Data Toolbar"),
  117. 1),
  118. 'misc' : ("toolbarMisc",
  119. _("Misc Toolbar"),
  120. 2),
  121. 'tools' : ("toolbarTools",
  122. _("Tools Toolbar"),
  123. 2),
  124. 'vector' : ("toolbarVector",
  125. _("Vector Toolbar"),
  126. 2),
  127. 'nviz' : ("toolbarNviz",
  128. _("3D view Toolbar"),
  129. 2),
  130. }
  131. if sys.platform == 'win32':
  132. self._toolbarsList = ('workspace', 'data',
  133. 'vector', 'tools', 'misc', 'nviz')
  134. else:
  135. self._toolbarsList = ('data', 'workspace',
  136. 'nviz', 'misc', 'tools', 'vector')
  137. for toolbar in self._toolbarsList:
  138. name, caption, row = self._toolbarsData[toolbar]
  139. self._auimgr.AddPane(self.toolbars[toolbar],
  140. wx.aui.AuiPaneInfo().
  141. Name(name).Caption(caption).
  142. ToolbarPane().Top().Row(row).
  143. LeftDockable(False).RightDockable(False).
  144. BottomDockable(False).TopDockable(True).
  145. CloseButton(False).Layer(2).
  146. BestSize((self.toolbars[toolbar].GetBestSize())))
  147. self._auimgr.GetPane('toolbarNviz').Hide()
  148. # bindings
  149. self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
  150. self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
  151. self._giface.mapCreated.connect(self.OnMapCreated)
  152. self._giface.updateMap.connect(self._updateCurrentMap)
  153. # minimal frame size
  154. self.SetMinSize(globalvar.GM_WINDOW_MIN_SIZE)
  155. # AUI stuff
  156. self._auimgr.AddPane(self.notebook, wx.aui.AuiPaneInfo().
  157. Left().CentrePane().BestSize((-1,-1)).Dockable(False).
  158. CloseButton(False).DestroyOnClose(True).Row(1).Layer(0))
  159. self._auimgr.Update()
  160. wx.CallAfter(self.notebook.SetSelectionByName, 'layers')
  161. # use default window layout ?
  162. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  163. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  164. try:
  165. x, y = map(int, dim.split(',')[0:2])
  166. w, h = map(int, dim.split(',')[2:4])
  167. self.SetPosition((x, y))
  168. self.SetSize((w, h))
  169. except:
  170. pass
  171. else:
  172. self.Centre()
  173. self.Layout()
  174. self.Show()
  175. # load workspace file if requested
  176. if self.workspaceFile:
  177. # load given workspace file
  178. if self.LoadWorkspaceFile(self.workspaceFile):
  179. self._setTitle()
  180. else:
  181. self.workspaceFile = None
  182. else:
  183. # start default initial display
  184. self.NewDisplay(show = False)
  185. # show map display widnow
  186. # -> OnSize() -> UpdateMap()
  187. for mapdisp in self.GetMapDisplay(onlyCurrent = False):
  188. mapdisp.Show()
  189. # redirect stderr to log area
  190. self._gconsole.Redirect()
  191. # fix goutput's pane size (required for Mac OSX)`
  192. self.goutput.SetSashPosition(int(self.GetSize()[1] * .8))
  193. self.workspaceChanged = False
  194. # start with layer manager on top
  195. if self.currentPage:
  196. self.GetMapDisplay().Raise()
  197. wx.CallAfter(self.Raise)
  198. def _setTitle(self):
  199. """!Set frame title"""
  200. if self.workspaceFile:
  201. self.SetTitle(self.baseTitle + " - " + os.path.splitext(os.path.basename(self.workspaceFile))[0])
  202. else:
  203. self.SetTitle(self.baseTitle)
  204. def _createMenuBar(self):
  205. """!Creates menu bar"""
  206. self.menubar = Menu(parent=self, model=self._menuTreeBuilder.GetModel(separators=True))
  207. self.SetMenuBar(self.menubar)
  208. self.menucmd = self.menubar.GetCmd()
  209. def _createTabMenu(self):
  210. """!Creates context menu for display tabs.
  211. Used to rename display.
  212. """
  213. menu = wx.Menu()
  214. item = wx.MenuItem(menu, id = wx.ID_ANY, text = _("Rename Map Display"))
  215. menu.AppendItem(item)
  216. self.Bind(wx.EVT_MENU, self.OnRenameDisplay, item)
  217. return menu
  218. def _setCopyingOfSelectedText(self):
  219. copy = UserSettings.Get(group = 'manager', key = 'copySelectedTextToClipboard', subkey = 'enabled')
  220. self.goutput.SetCopyingOfSelectedText(copy)
  221. def IsPaneShown(self, name):
  222. """!Check if pane (toolbar, ...) of given name is currently shown"""
  223. if self._auimgr.GetPane(name).IsOk():
  224. return self._auimgr.GetPane(name).IsShown()
  225. return False
  226. def _createNoteBook(self):
  227. """!Creates notebook widgets"""
  228. self.notebook = GNotebook(parent = self, style = globalvar.FNPageDStyle)
  229. # create displays notebook widget and add it to main notebook page
  230. cbStyle = globalvar.FNPageStyle
  231. if globalvar.hasAgw:
  232. self.notebookLayers = FN.FlatNotebook(self, id = wx.ID_ANY, agwStyle = cbStyle)
  233. else:
  234. self.notebookLayers = FN.FlatNotebook(self, id = wx.ID_ANY, style = cbStyle)
  235. self.notebookLayers.SetTabAreaColour(globalvar.FNPageColor)
  236. menu = self._createTabMenu()
  237. self.notebookLayers.SetRightClickMenu(menu)
  238. self.notebook.AddPage(page = self.notebookLayers, text = _("Map layers"), name = 'layers')
  239. # create 'command output' text area
  240. self._gconsole = GConsole(guiparent = self, giface = self._giface,
  241. ignoredCmdPattern = '^d\..*|^r[3]?\.mapcalc$|^i.group$|^r.in.gdal$|'
  242. '^r.external$|^r.external.out$|'
  243. '^v.in.ogr$|^v.external$|^v.external.out$')
  244. self.goutput = GConsoleWindow(parent = self, gconsole = self._gconsole,
  245. menuModel=self._moduleTreeBuilder.GetModel(),
  246. gcstyle = GC_PROMPT)
  247. self.notebook.AddPage(page = self.goutput, text = _("Command console"), name = 'output')
  248. self.goutput.showNotification.connect(lambda message: self.SetStatusText(message))
  249. self._gconsole.mapCreated.connect(self.OnMapCreated)
  250. self.goutput.contentChanged.connect(
  251. lambda notification: self._switchPage(notification))
  252. self._gconsole.Bind(EVT_IGNORED_CMD_RUN,
  253. lambda event: self.RunSpecialCmd(event.cmd))
  254. self._setCopyingOfSelectedText()
  255. # create 'search module' notebook page
  256. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'search'):
  257. self.search = SearchModuleWindow(parent = self, model=self._moduleTreeBuilder.GetModel())
  258. self.search.showNotification.connect(lambda message: self.SetStatusText(message))
  259. self.notebook.AddPage(page = self.search, text = _("Search modules"), name = 'search')
  260. else:
  261. self.search = None
  262. # create 'python shell' notebook page
  263. if not UserSettings.Get(group = 'manager', key = 'hideTabs', subkey = 'pyshell'):
  264. self.pyshell = PyShellWindow(parent = self)
  265. self.notebook.AddPage(page = self.pyshell, text = _("Python shell"), name = 'pyshell')
  266. else:
  267. self.pyshell = None
  268. # bindings
  269. self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnCBPageChanged)
  270. self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
  271. self.notebookLayers.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CLOSING, self.OnCBPageClosed)
  272. return self.notebook
  273. def AddNvizTools(self, firstTime):
  274. """!Add nviz notebook page
  275. @param firstTime if a mapdisplay is starting 3D mode for the first time
  276. """
  277. Debug.msg(5, "GMFrame.AddNvizTools()")
  278. if not haveNviz:
  279. return
  280. from nviz.main import NvizToolWindow
  281. # show toolbar
  282. self._auimgr.GetPane('toolbarNviz').Show()
  283. # reorder other toolbars
  284. for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc','toolbarNviz')):
  285. self._auimgr.GetPane(toolbar).Row(2).Position(pos)
  286. self._auimgr.Update()
  287. # create nviz tools tab
  288. self.nviz = NvizToolWindow(parent = self,
  289. display = self.GetMapDisplay())
  290. idx = self.notebook.GetPageIndexByName('layers')
  291. self.notebook.InsertPage(indx = idx + 1, page = self.nviz, text = _("3D view"), name = 'nviz')
  292. self.notebook.SetSelectionByName('nviz')
  293. # this is a bit strange here since a new window is created everytime
  294. if not firstTime:
  295. for page in ('view', 'light', 'fringe', 'constant', 'cplane', 'animation'):
  296. self.nviz.UpdatePage(page)
  297. def RemoveNvizTools(self):
  298. """!Remove nviz notebook page"""
  299. # if more mapwindow3D were possible, check here if nb page should be removed
  300. self.notebook.SetSelectionByName('layers')
  301. self.notebook.DeletePage('nviz')
  302. # hide toolbar
  303. self._auimgr.GetPane('toolbarNviz').Hide()
  304. for pos, toolbar in enumerate(('toolbarVector', 'toolbarTools', 'toolbarMisc')):
  305. self._auimgr.GetPane(toolbar).Row(2).Position(pos)
  306. self._auimgr.Update()
  307. def WorkspaceChanged(self):
  308. """!Update window title"""
  309. if not self.workspaceChanged:
  310. self.workspaceChanged = True
  311. if self.workspaceFile:
  312. self._setTitle()
  313. def OnLocationWizard(self, event):
  314. """!Launch location wizard"""
  315. from location_wizard.wizard import LocationWizard
  316. from location_wizard.dialogs import RegionDef
  317. gWizard = LocationWizard(parent = self,
  318. grassdatabase = grass.gisenv()['GISDBASE'])
  319. location = gWizard.location
  320. if location != None:
  321. dlg = wx.MessageDialog(parent = self,
  322. message = _('Location <%s> created.\n\n'
  323. 'Do you want to switch to the '
  324. 'new location?') % location,
  325. caption=_("Switch to new location?"),
  326. style = wx.YES_NO | wx.NO_DEFAULT |
  327. wx.ICON_QUESTION | wx.CENTRE)
  328. ret = dlg.ShowModal()
  329. dlg.Destroy()
  330. if ret == wx.ID_YES:
  331. if RunCommand('g.mapset', parent = self,
  332. location = location,
  333. mapset = 'PERMANENT') != 0:
  334. return
  335. # close current workspace and create new one
  336. self.OnWorkspaceClose()
  337. self.OnWorkspaceNew()
  338. GMessage(parent = self,
  339. message = _("Current location is <%(loc)s>.\n"
  340. "Current mapset is <%(mapset)s>.") % \
  341. { 'loc' : location, 'mapset' : 'PERMANENT' })
  342. # code duplication with gis_set.py
  343. dlg = wx.MessageDialog(parent = self,
  344. message = _("Do you want to set the default "
  345. "region extents and resolution now?"),
  346. caption = _("Location <%s> created") % location,
  347. style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
  348. dlg.CenterOnScreen()
  349. if dlg.ShowModal() == wx.ID_YES:
  350. dlg.Destroy()
  351. defineRegion = RegionDef(self, location = location)
  352. defineRegion.CenterOnScreen()
  353. defineRegion.ShowModal()
  354. defineRegion.Destroy()
  355. else:
  356. dlg.Destroy()
  357. def OnSettingsChanged(self):
  358. """!Here can be functions which have to be called
  359. after receiving settingsChanged signal.
  360. Now only set copying of selected text to clipboard (in goutput).
  361. """
  362. ### self._createMenuBar() # bug when menu is re-created on the fly
  363. self._setCopyingOfSelectedText()
  364. def OnGCPManager(self, event):
  365. """!Launch georectifier module
  366. """
  367. GCPWizard(self, self._giface)
  368. def OnGModeler(self, event):
  369. """!Launch Graphical Modeler"""
  370. win = ModelFrame(parent = self, giface = self._giface)
  371. win.CentreOnScreen()
  372. win.Show()
  373. def OnPsMap(self, event):
  374. """!Launch Cartographic Composer
  375. """
  376. win = PsMapFrame(parent = self)
  377. win.CentreOnScreen()
  378. win.Show()
  379. def OnMapSwipe(self, event):
  380. """!Launch Map Swipe"""
  381. win = SwipeMapFrame(parent=self, giface=self._giface)
  382. rasters = []
  383. tree = self.GetLayerTree()
  384. if tree:
  385. for layer in tree.GetSelections():
  386. if tree.GetLayerInfo(layer, key = 'maplayer').GetType() != 'raster':
  387. continue
  388. rasters.append(tree.GetLayerInfo(layer, key = 'maplayer').GetName())
  389. if len(rasters) >= 1:
  390. win.SetFirstRaster(rasters[0])
  391. if len(rasters) >= 2:
  392. win.SetSecondRaster(rasters[1])
  393. win.SetRasterNames()
  394. win.CentreOnScreen()
  395. win.Show()
  396. def OnRLiSetup(self, event):
  397. """!Launch r.li Setup"""
  398. win = RLiSetupFrame(parent = self)
  399. win.CentreOnScreen()
  400. win.Show()
  401. def OnDone(self, cmd, returncode):
  402. """Command execution finished"""
  403. if hasattr(self, "model"):
  404. self.model.DeleteIntermediateData(log = self._gconsole)
  405. del self.model
  406. self.SetStatusText('')
  407. def OnRunModel(self, event):
  408. """!Run model"""
  409. filename = ''
  410. dlg = wx.FileDialog(parent = self, message =_("Choose model to run"),
  411. defaultDir = os.getcwd(),
  412. wildcard = _("GRASS Model File (*.gxm)|*.gxm"))
  413. if dlg.ShowModal() == wx.ID_OK:
  414. filename = dlg.GetPath()
  415. if not filename:
  416. dlg.Destroy()
  417. return
  418. self.model = Model()
  419. self.model.LoadModel(filename)
  420. self.model.Run(log = self._goutput, onDone = self.OnDone, parent = self)
  421. dlg.Destroy()
  422. def OnMapsets(self, event):
  423. """!Launch mapset access dialog
  424. """
  425. dlg = MapsetAccess(parent = self, id = wx.ID_ANY)
  426. dlg.CenterOnScreen()
  427. if dlg.ShowModal() == wx.ID_OK:
  428. ms = dlg.GetMapsets()
  429. RunCommand('g.mapsets',
  430. parent = self,
  431. mapset = '%s' % ','.join(ms),
  432. operation = 'set')
  433. def OnCBPageChanged(self, event):
  434. """!Page in notebook (display) changed"""
  435. self.currentPage = self.notebookLayers.GetCurrentPage()
  436. self.currentPageNum = self.notebookLayers.GetSelection()
  437. try:
  438. self.GetMapDisplay().SetFocus()
  439. self.GetMapDisplay().Raise()
  440. except:
  441. pass
  442. event.Skip()
  443. def OnPageChanged(self, event):
  444. """!Page in notebook changed"""
  445. page = event.GetSelection()
  446. if page == self.notebook.GetPageIndexByName('output'):
  447. wx.CallAfter(self.goutput.ResetFocus)
  448. self.SetStatusText('', 0)
  449. event.Skip()
  450. def OnCBPageClosed(self, event):
  451. """!Page of notebook closed
  452. Also close associated map display
  453. """
  454. if UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  455. maptree = self.GetLayerTree()
  456. if self.workspaceFile:
  457. message = _("Do you want to save changes in the workspace?")
  458. else:
  459. message = _("Do you want to store current settings "
  460. "to workspace file?")
  461. # ask user to save current settings
  462. if maptree.GetCount() > 0:
  463. name = self.notebookLayers.GetPageText(self.currentPageNum)
  464. dlg = wx.MessageDialog(self,
  465. message = message,
  466. caption = _("Close Map Display %s") % name,
  467. style = wx.YES_NO | wx.YES_DEFAULT |
  468. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  469. ret = dlg.ShowModal()
  470. if ret == wx.ID_YES:
  471. if not self.workspaceFile:
  472. self.OnWorkspaceSaveAs()
  473. else:
  474. self.SaveToWorkspaceFile(self.workspaceFile)
  475. elif ret == wx.ID_CANCEL:
  476. event.Veto()
  477. dlg.Destroy()
  478. return
  479. dlg.Destroy()
  480. self.notebookLayers.GetPage(event.GetSelection()).maptree.Map.Clean()
  481. self.notebookLayers.GetPage(event.GetSelection()).maptree.Close(True)
  482. self.currentPage = None
  483. event.Skip()
  484. def _switchPageHandler(self, event, notification):
  485. self._switchPage(notification=notification)
  486. event.Skip()
  487. def _switchPage(self, notification):
  488. """!Manages @c 'output' notebook page according to event notification."""
  489. if notification == Notification.HIGHLIGHT:
  490. self.notebook.HighlightPageByName('output')
  491. if notification == Notification.MAKE_VISIBLE:
  492. self.notebook.SetSelectionByName('output')
  493. if notification == Notification.RAISE_WINDOW:
  494. self.notebook.SetSelectionByName('output')
  495. self.SetFocus()
  496. self.Raise()
  497. def RunSpecialCmd(self, command):
  498. """!Run command from command line, check for GUI wrappers"""
  499. if re.compile('^d\..*').search(command[0]):
  500. self.RunDisplayCmd(command)
  501. elif re.compile('r[3]?\.mapcalc').search(command[0]):
  502. self.OnMapCalculator(event = None, cmd = command)
  503. elif command[0] == 'i.group':
  504. self.OnEditImageryGroups(event = None, cmd = command)
  505. elif command[0] == 'r.in.gdal':
  506. self.OnImportGdalLayers(event = None, cmd = command)
  507. elif command[0] == 'r.external':
  508. self.OnLinkGdalLayers(event = None, cmd = command)
  509. elif command[0] == 'r.external.out':
  510. self.OnRasterOutputFormat(event = None)
  511. elif command[0] == 'v.in.ogr':
  512. self.OnImportOgrLayers(event = None, cmd = command)
  513. elif command[0] == 'v.external':
  514. self.OnLinkOgrLayers(event = None, cmd = command)
  515. elif command[0] == 'v.external.out':
  516. self.OnVectorOutputFormat(event = None)
  517. else:
  518. raise ValueError('Layer Manager special command (%s)'
  519. ' not supported.' % ' '.join(command))
  520. def RunDisplayCmd(self, command):
  521. """!Handles display commands.
  522. @param command command in a list
  523. """
  524. if not self.currentPage:
  525. self.NewDisplay(show = True)
  526. try:
  527. # display GRASS commands
  528. layertype = command2ltype[command[0]]
  529. except KeyError:
  530. GMessage(parent = self,
  531. message = _("Command '%s' not yet implemented in the WxGUI. "
  532. "Try adding it as a command layer instead.") % command[0])
  533. return
  534. if layertype == 'barscale':
  535. if len(command) > 1:
  536. self.GetMapDisplay().AddBarscale(cmd = command, showDialog = False)
  537. else:
  538. self.GetMapDisplay().AddBarscale(showDialog = True)
  539. elif layertype == 'rastleg':
  540. if len(command) > 1:
  541. self.GetMapDisplay().AddLegend(cmd = command, showDialog = False)
  542. else:
  543. self.GetMapDisplay().AddLegend(showDialog = True)
  544. elif layertype == 'redraw':
  545. self.GetMapDisplay().OnRender(None)
  546. else:
  547. # add layer into layer tree
  548. lname, found = GetLayerNameFromCmd(command, fullyQualified = True,
  549. layerType = layertype)
  550. self.GetLayerTree().AddLayer(ltype = layertype,
  551. lname = lname,
  552. lcmd = command)
  553. def GetLayerNotebook(self):
  554. """!Get Layers Notebook"""
  555. return self.notebookLayers
  556. def GetLayerTree(self):
  557. """!Get current layer tree
  558. @return LayerTree instance
  559. @return None no layer tree selected
  560. """
  561. if self.currentPage:
  562. return self.currentPage.maptree
  563. return None
  564. def GetMapDisplay(self, onlyCurrent = True):
  565. """!Get current map display
  566. @param onlyCurrent True to return only active mapdisplay
  567. False for list of all mapdisplays
  568. @return MapFrame instance (or list)
  569. @return None no mapdisplay selected
  570. """
  571. if onlyCurrent:
  572. if self.currentPage:
  573. return self.GetLayerTree().GetMapDisplay()
  574. else:
  575. return None
  576. else: # -> return list of all mapdisplays
  577. mlist = list()
  578. for idx in range(0, self.notebookLayers.GetPageCount()):
  579. mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay())
  580. return mlist
  581. def GetLogWindow(self):
  582. """!Gets console for command output and messages"""
  583. return self._gconsole
  584. def GetToolbar(self, name):
  585. """!Returns toolbar if exists else None"""
  586. if name in self.toolbars:
  587. return self.toolbars[name]
  588. return None
  589. def GetMenuCmd(self, event):
  590. """!Get GRASS command from menu item
  591. Return command as a list"""
  592. layer = None
  593. if event:
  594. cmd = self.menucmd[event.GetId()]
  595. else:
  596. cmd = ''
  597. try:
  598. cmdlist = cmd.split(' ')
  599. except: # already list?
  600. cmdlist = cmd
  601. # check list of dummy commands for GUI modules that do not have GRASS
  602. # bin modules or scripts.
  603. if cmd in ['vcolors', 'r.mapcalc', 'r3.mapcalc']:
  604. return cmdlist
  605. try:
  606. layer = self.GetLayerTree().layer_selected
  607. name = self.GetLayerTree().GetLayerInfo(layer, key = 'maplayer').name
  608. type = self.GetLayerTree().GetLayerInfo(layer, key = 'type')
  609. except:
  610. layer = None
  611. if layer and len(cmdlist) == 1: # only if no paramaters given
  612. if (type == 'raster' and cmdlist[0][0] == 'r' and cmdlist[0][1] != '3') or \
  613. (type == 'vector' and cmdlist[0][0] == 'v'):
  614. input = GUI().GetCommandInputMapParamKey(cmdlist[0])
  615. if input:
  616. cmdlist.append("%s=%s" % (input, name))
  617. return cmdlist
  618. def RunMenuCmd(self, event = None, cmd = []):
  619. """!Run command selected from menu"""
  620. if event:
  621. cmd = self.GetMenuCmd(event)
  622. self._gconsole.RunCmd(cmd)
  623. def OnMenuCmd(self, event = None, cmd = []):
  624. """!Parse command selected from menu"""
  625. if event:
  626. cmd = self.GetMenuCmd(event)
  627. GUI(parent=self, giface=self._giface).ParseCommand(cmd)
  628. def OnVNet(self, event):
  629. """Vector network analysis tool"""
  630. if self.GetMapDisplay():
  631. self.GetMapDisplay().OnVNet(event)
  632. else:
  633. self.NewDisplay(show = True).OnVNet(event)
  634. def OnVDigit(self, event):
  635. """!Start vector digitizer
  636. """
  637. if not self.currentPage:
  638. self.MsgNoLayerSelected()
  639. return
  640. tree = self.GetLayerTree()
  641. layer = tree.layer_selected
  642. # no map layer selected
  643. if not layer:
  644. self.MsgNoLayerSelected()
  645. return
  646. # available only for vector map layers
  647. try:
  648. mapLayer = tree.GetLayerInfo(layer, key = 'maplayer')
  649. except:
  650. mapLayer = None
  651. if not mapLayer or mapLayer.GetType() != 'vector':
  652. GMessage(parent = self,
  653. message = _("Selected map layer is not vector."))
  654. return
  655. if mapLayer.GetMapset() != grass.gisenv()['MAPSET']:
  656. GMessage(parent = self,
  657. message = _("Editing is allowed only for vector maps from the "
  658. "current mapset."))
  659. return
  660. if not tree.GetLayerInfo(layer):
  661. return
  662. dcmd = tree.GetLayerInfo(layer, key = 'cmd')
  663. if not dcmd:
  664. return
  665. digitToolbar = self.GetMapDisplay().GetToolbar('vdigit')
  666. if digitToolbar:
  667. stopOnly = False
  668. if mapLayer is digitToolbar.GetLayer():
  669. stopOnly = True
  670. tree.OnStopEditing(None) # TODO: change to signal
  671. if stopOnly:
  672. return
  673. tree.OnStartEditing(None) # TODO: change to signal
  674. def OnRunScript(self, event):
  675. """!Run user-defined script"""
  676. # open dialog and choose script file
  677. dlg = wx.FileDialog(parent = self, message = _("Choose script file to run"),
  678. defaultDir = os.getcwd(),
  679. wildcard = _("Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
  680. filename = None
  681. if dlg.ShowModal() == wx.ID_OK:
  682. filename = dlg.GetPath()
  683. if not filename:
  684. return False
  685. if not os.path.exists(filename):
  686. GError(parent = self,
  687. message = _("Script file '%s' doesn't exist. "
  688. "Operation canceled.") % filename)
  689. return
  690. # check permission
  691. if not os.access(filename, os.X_OK):
  692. dlg = wx.MessageDialog(self,
  693. message = _("Script <%s> is not executable. "
  694. "Do you want to set the permissions "
  695. "that allows you to run this script "
  696. "(note that you must be the owner of the file)?" % \
  697. os.path.basename(filename)),
  698. caption = _("Set permission?"),
  699. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  700. if dlg.ShowModal() != wx.ID_YES:
  701. return
  702. dlg.Destroy()
  703. try:
  704. mode = stat.S_IMODE(os.lstat(filename)[stat.ST_MODE])
  705. os.chmod(filename, mode | stat.S_IXUSR)
  706. except OSError:
  707. GError(_("Unable to set permission. Operation canceled."), parent = self)
  708. return
  709. # check GRASS_ADDON_PATH
  710. addonPath = os.getenv('GRASS_ADDON_PATH', [])
  711. if addonPath:
  712. addonPath = addonPath.split(os.pathsep)
  713. dirName = os.path.dirname(filename)
  714. if dirName not in addonPath:
  715. addonPath.append(dirName)
  716. dlg = wx.MessageDialog(self,
  717. message = _("Directory '%s' is not defined in GRASS_ADDON_PATH. "
  718. "Do you want add this directory to GRASS_ADDON_PATH?") % \
  719. dirName,
  720. caption = _("Update Addons path?"),
  721. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  722. if dlg.ShowModal() == wx.ID_YES:
  723. SetAddOnPath(os.pathsep.join(addonPath), key = 'PATH')
  724. dlg.Destroy()
  725. self._gconsole.WriteCmdLog(_("Launching script '%s'...") % filename)
  726. self._gconsole.RunCmd([filename])
  727. def OnChangeLocation(self, event):
  728. """Change current location"""
  729. dlg = LocationDialog(parent = self)
  730. if dlg.ShowModal() == wx.ID_OK:
  731. location, mapset = dlg.GetValues()
  732. dlg.Destroy()
  733. if not location or not mapset:
  734. GError(parent = self,
  735. message = _("No location/mapset provided. Operation canceled."))
  736. return # this should not happen
  737. if RunCommand('g.mapset', parent = self,
  738. location = location,
  739. mapset = mapset) != 0:
  740. return # error reported
  741. # close current workspace and create new one
  742. self.OnWorkspaceClose()
  743. self.OnWorkspaceNew()
  744. GMessage(parent = self,
  745. message = _("Current location is <%(loc)s>.\n"
  746. "Current mapset is <%(mapset)s>.") % \
  747. { 'loc' : location, 'mapset' : mapset })
  748. def OnCreateMapset(self, event):
  749. """!Create new mapset"""
  750. dlg = wx.TextEntryDialog(parent = self,
  751. message = _('Enter name for new mapset:'),
  752. caption = _('Create new mapset'))
  753. if dlg.ShowModal() == wx.ID_OK:
  754. mapset = dlg.GetValue()
  755. if not mapset:
  756. GError(parent = self,
  757. message = _("No mapset provided. Operation canceled."))
  758. return
  759. ret = RunCommand('g.mapset',
  760. parent = self,
  761. flags = 'c',
  762. mapset = mapset)
  763. if ret == 0:
  764. GMessage(parent = self,
  765. message = _("Current mapset is <%s>.") % mapset)
  766. def OnChangeMapset(self, event):
  767. """Change current mapset"""
  768. dlg = MapsetDialog(parent = self)
  769. if dlg.ShowModal() == wx.ID_OK:
  770. mapset = dlg.GetMapset()
  771. dlg.Destroy()
  772. if not mapset:
  773. GError(parent = self,
  774. message = _("No mapset provided. Operation canceled."))
  775. return
  776. if RunCommand('g.mapset',
  777. parent = self,
  778. mapset = mapset) == 0:
  779. GMessage(parent = self,
  780. message = _("Current mapset is <%s>.") % mapset)
  781. def OnChangeCWD(self, event):
  782. """!Change current working directory
  783. """
  784. dlg = wx.DirDialog(parent = self, message = _("Choose a working directory"),
  785. defaultPath = os.getcwd(), style = wx.DD_CHANGE_DIR)
  786. if dlg.ShowModal() == wx.ID_OK:
  787. self.cwdPath = dlg.GetPath() # is saved in the workspace
  788. def GetCwdPath(self):
  789. """!Get current working directory or None"""
  790. return self.cwdPath
  791. def OnNewVector(self, event):
  792. """!Create new vector map layer"""
  793. dlg = CreateNewVector(self, giface=self._giface,
  794. cmd=(('v.edit',
  795. {'tool': 'create'},
  796. 'map')))
  797. if not dlg:
  798. return
  799. name = dlg.GetName(full = True)
  800. if name and dlg.IsChecked('add'):
  801. # add layer to map layer tree
  802. self.GetLayerTree().AddLayer(ltype = 'vector',
  803. lname = name,
  804. lcmd = ['d.vect', 'map=%s' % name])
  805. dlg.Destroy()
  806. def OnSystemInfo(self, event):
  807. """!Print system information"""
  808. vInfo = grass.version()
  809. # check also OSGeo4W on MS Windows
  810. if sys.platform == 'win32' and \
  811. not os.path.exists(os.path.join(os.getenv("GISBASE"), "WinGRASS-README.url")):
  812. osgeo4w = ' (OSGeo4W)'
  813. else:
  814. osgeo4w = ''
  815. self._gconsole.WriteCmdLog(_("System Info"))
  816. # platform from UTF-8 conversion was added because of the Fedora 19 release
  817. # which has the name "Schrödinger’s cat" (umlaut and special ' character)
  818. # which appears in the platform.platform() string
  819. self._gconsole.WriteLog("%s: %s\n"
  820. "%s: %s\n"
  821. "%s: %s\n"
  822. # "%s: %s (%s)\n"
  823. "GDAL/OGR: %s\n"
  824. "PROJ.4: %s\n"
  825. "GEOS: %s\n"
  826. "SQLite: %s\n"
  827. "Python: %s\n"
  828. "wxPython: %s\n"
  829. "%s: %s%s\n"% (_("GRASS version"), vInfo['version'],
  830. _("GRASS SVN Revision"), vInfo['revision'],
  831. _("Build Date"), vInfo['build_date'],
  832. # _("GIS Library Revision"), vInfo['libgis_revision'], vInfo['libgis_date'].split(' ', 1)[0],
  833. vInfo['gdal'], vInfo['proj4'], vInfo['geos'], vInfo['sqlite'],
  834. platform.python_version(),
  835. wx.__version__,
  836. _("Platform"), platform.platform().decode('utf8', 'replace'), osgeo4w),
  837. notification=Notification.MAKE_VISIBLE)
  838. self._gconsole.WriteCmdLog(' ')
  839. def OnAboutGRASS(self, event):
  840. """!Display 'About GRASS' dialog"""
  841. win = AboutWindow(self)
  842. win.CentreOnScreen()
  843. win.Show(True)
  844. def _popupMenu(self, data):
  845. """!Create popup menu
  846. """
  847. menu = wx.Menu()
  848. for key, handler in data:
  849. if key is None:
  850. menu.AppendSeparator()
  851. continue
  852. item = wx.MenuItem(menu, wx.ID_ANY, LMIcons[key].GetLabel())
  853. item.SetBitmap(LMIcons[key].GetBitmap(self.iconsize))
  854. menu.AppendItem(item)
  855. self.Bind(wx.EVT_MENU, handler, item)
  856. # create menu
  857. self.PopupMenu(menu)
  858. menu.Destroy()
  859. def OnImportMenu(self, event):
  860. """!Import maps menu (import, link)
  861. """
  862. self._popupMenu((('rastImport', self.OnImportGdalLayers),
  863. ('rastLink', self.OnLinkGdalLayers),
  864. ('rastOut', self.OnRasterOutputFormat),
  865. (None, None),
  866. ('vectImport', self.OnImportOgrLayers),
  867. ('vectLink', self.OnLinkOgrLayers),
  868. ('vectOut', self.OnVectorOutputFormat)))
  869. def OnWorkspaceNew(self, event = None):
  870. """!Create new workspace file
  871. Erase current workspace settings first
  872. """
  873. Debug.msg(4, "GMFrame.OnWorkspaceNew():")
  874. # start new map display if no display is available
  875. if not self.currentPage:
  876. self.NewDisplay()
  877. maptree = self.GetLayerTree()
  878. # ask user to save current settings
  879. if self.workspaceFile and self.workspaceChanged:
  880. self.OnWorkspaceSave()
  881. elif self.workspaceFile is None and maptree.GetCount() > 0:
  882. dlg = wx.MessageDialog(self, message = _("Current workspace is not empty. "
  883. "Do you want to store current settings "
  884. "to workspace file?"),
  885. caption = _("Create new workspace?"),
  886. style = wx.YES_NO | wx.YES_DEFAULT | \
  887. wx.CANCEL | wx.ICON_QUESTION)
  888. ret = dlg.ShowModal()
  889. if ret == wx.ID_YES:
  890. self.OnWorkspaceSaveAs()
  891. elif ret == wx.ID_CANCEL:
  892. dlg.Destroy()
  893. return
  894. dlg.Destroy()
  895. # delete all items
  896. maptree.DeleteAllItems()
  897. # add new root element
  898. maptree.root = maptree.AddRoot("Map Layers")
  899. self.GetLayerTree().SetPyData(maptree.root, (None,None))
  900. # no workspace file loaded
  901. self.workspaceFile = None
  902. self.workspaceChanged = False
  903. self._setTitle()
  904. def OnWorkspaceOpen(self, event = None):
  905. """!Open file with workspace definition"""
  906. dlg = wx.FileDialog(parent = self, message = _("Choose workspace file"),
  907. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"))
  908. filename = ''
  909. if dlg.ShowModal() == wx.ID_OK:
  910. filename = dlg.GetPath()
  911. if filename == '':
  912. return
  913. Debug.msg(4, "GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
  914. # delete current layer tree content
  915. self.OnWorkspaceClose()
  916. self.LoadWorkspaceFile(filename)
  917. self.workspaceFile = filename
  918. self._setTitle()
  919. def LoadWorkspaceFile(self, filename):
  920. """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
  921. @todo Validate against DTD
  922. @return True on success
  923. @return False on error
  924. """
  925. # dtd
  926. # dtdFilename = os.path.join(globalvar.ETCWXDIR, "xml", "grass-gxw.dtd")
  927. # parse workspace file
  928. try:
  929. gxwXml = ProcessWorkspaceFile(etree.parse(filename))
  930. except Exception, e:
  931. GError(parent = self,
  932. message = _("Reading workspace file <%s> failed.\n"
  933. "Invalid file, unable to parse XML document.") % filename)
  934. return
  935. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  936. parent = self)
  937. wx.Yield()
  938. #
  939. # load layer manager window properties
  940. #
  941. if UserSettings.Get(group = 'general', key = 'workspace', subkey = ['posManager', 'enabled']) is False:
  942. if gxwXml.layerManager['pos']:
  943. self.SetPosition(gxwXml.layerManager['pos'])
  944. if gxwXml.layerManager['size']:
  945. self.SetSize(gxwXml.layerManager['size'])
  946. if gxwXml.layerManager['cwd']:
  947. self.cwdPath = gxwXml.layerManager['cwd']
  948. if os.path.isdir(self.cwdPath):
  949. os.chdir(self.cwdPath)
  950. #
  951. # start map displays first (list of layers can be empty)
  952. #
  953. displayId = 0
  954. mapdisplay = list()
  955. for display in gxwXml.displays:
  956. mapdisp = self.NewDisplay(name = display['name'], show = False)
  957. mapdisplay.append(mapdisp)
  958. maptree = self.notebookLayers.GetPage(displayId).maptree
  959. # set windows properties
  960. mapdisp.SetProperties(render = display['render'],
  961. mode = display['mode'],
  962. showCompExtent = display['showCompExtent'],
  963. alignExtent = display['alignExtent'],
  964. constrainRes = display['constrainRes'],
  965. projection = display['projection']['enabled'])
  966. if display['projection']['enabled']:
  967. if display['projection']['epsg']:
  968. UserSettings.Set(group = 'display', key = 'projection', subkey = 'epsg',
  969. value = display['projection']['epsg'])
  970. if display['projection']['proj']:
  971. UserSettings.Set(group = 'display', key = 'projection', subkey = 'proj4',
  972. value = display['projection']['proj'])
  973. # set position and size of map display
  974. if not UserSettings.Get(group = 'general', key = 'workspace', subkey = ['posDisplay', 'enabled']):
  975. if display['pos']:
  976. mapdisp.SetPosition(display['pos'])
  977. if display['size']:
  978. mapdisp.SetSize(display['size'])
  979. # set extent if defined
  980. if display['extent']:
  981. w, s, e, n, b, t = display['extent']
  982. region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
  983. mapdisp.GetWindow().ResetZoomHistory()
  984. mapdisp.GetWindow().ZoomHistory(region['n'],
  985. region['s'],
  986. region['e'],
  987. region['w'])
  988. displayId += 1
  989. mapdisp.Show() # show mapdisplay
  990. maptree = None
  991. selectList = [] # list of selected layers
  992. #
  993. # load list of map layers
  994. #
  995. for layer in gxwXml.layers:
  996. display = layer['display']
  997. maptree = self.notebookLayers.GetPage(display).maptree
  998. newItem = maptree.AddLayer(ltype = layer['type'],
  999. lname = layer['name'],
  1000. lchecked = layer['checked'],
  1001. lopacity = layer['opacity'],
  1002. lcmd = layer['cmd'],
  1003. lgroup = layer['group'],
  1004. lnviz = layer['nviz'],
  1005. lvdigit = layer['vdigit'])
  1006. if 'selected' in layer:
  1007. selectList.append((maptree, newItem, layer['selected']))
  1008. for maptree, layer, selected in selectList:
  1009. if selected:
  1010. if not layer.IsSelected():
  1011. maptree.SelectItem(layer, select=True)
  1012. else:
  1013. maptree.SelectItem(layer, select=False)
  1014. busy.Destroy()
  1015. for idx, mdisp in enumerate(mapdisplay):
  1016. ### avoid double-rendering when loading workspace
  1017. ### mdisp.MapWindow2D.UpdateMap()
  1018. # nviz
  1019. if gxwXml.displays[idx]['viewMode'] == '3d':
  1020. mdisp.AddNviz()
  1021. self.nviz.UpdateState(view = gxwXml.nviz_state['view'],
  1022. iview = gxwXml.nviz_state['iview'],
  1023. light = gxwXml.nviz_state['light'])
  1024. mdisp.MapWindow3D.constants = gxwXml.nviz_state['constants']
  1025. for idx, constant in enumerate(mdisp.MapWindow3D.constants):
  1026. mdisp.MapWindow3D.AddConstant(constant, idx + 1)
  1027. for page in ('view', 'light', 'fringe', 'constant', 'cplane'):
  1028. self.nviz.UpdatePage(page)
  1029. self.nviz.UpdateSettings()
  1030. mdisp.toolbars['map'].combo.SetSelection(1)
  1031. return True
  1032. def OnWorkspaceLoadGrcFile(self, event):
  1033. """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
  1034. dlg = wx.FileDialog(parent = self, message = _("Choose GRC file to load"),
  1035. defaultDir = os.getcwd(), wildcard = _("Old GRASS Workspace File (*.grc)|*.grc"))
  1036. filename = ''
  1037. if dlg.ShowModal() == wx.ID_OK:
  1038. filename = dlg.GetPath()
  1039. if filename == '':
  1040. return
  1041. Debug.msg(4, "GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
  1042. # start new map display if no display is available
  1043. if not self.currentPage:
  1044. self.NewDisplay()
  1045. busy = wx.BusyInfo(message = _("Please wait, loading workspace..."),
  1046. parent = self)
  1047. wx.Yield()
  1048. maptree = None
  1049. for layer in ProcessGrcFile(filename).read(self):
  1050. maptree = self.notebookLayers.GetPage(layer['display']).maptree
  1051. newItem = maptree.AddLayer(ltype = layer['type'],
  1052. lname = layer['name'],
  1053. lchecked = layer['checked'],
  1054. lopacity = layer['opacity'],
  1055. lcmd = layer['cmd'],
  1056. lgroup = layer['group'])
  1057. busy.Destroy()
  1058. if maptree:
  1059. # reverse list of map layers
  1060. maptree.Map.ReverseListOfLayers()
  1061. def OnWorkspaceSaveAs(self, event = None):
  1062. """!Save workspace definition to selected file"""
  1063. dlg = wx.FileDialog(parent = self, message = _("Choose file to save current workspace"),
  1064. defaultDir = os.getcwd(), wildcard = _("GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
  1065. filename = ''
  1066. if dlg.ShowModal() == wx.ID_OK:
  1067. filename = dlg.GetPath()
  1068. if filename == '':
  1069. return False
  1070. # check for extension
  1071. if filename[-4:] != ".gxw":
  1072. filename += ".gxw"
  1073. if os.path.exists(filename):
  1074. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  1075. "Do you want to overwrite this file?") % filename,
  1076. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1077. if dlg.ShowModal() != wx.ID_YES:
  1078. dlg.Destroy()
  1079. return False
  1080. Debug.msg(4, "GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
  1081. self.SaveToWorkspaceFile(filename)
  1082. self.workspaceFile = filename
  1083. self._setTitle()
  1084. def OnWorkspaceSave(self, event = None):
  1085. """!Save file with workspace definition"""
  1086. if self.workspaceFile:
  1087. dlg = wx.MessageDialog(self, message = _("Workspace file <%s> already exists. "
  1088. "Do you want to overwrite this file?") % \
  1089. self.workspaceFile,
  1090. caption = _("Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1091. if dlg.ShowModal() == wx.ID_NO:
  1092. dlg.Destroy()
  1093. else:
  1094. Debug.msg(4, "GMFrame.OnWorkspaceSave(): filename=%s" % self.workspaceFile)
  1095. self.SaveToWorkspaceFile(self.workspaceFile)
  1096. self._setTitle()
  1097. self.workspaceChanged = False
  1098. else:
  1099. self.OnWorkspaceSaveAs()
  1100. def SaveToWorkspaceFile(self, filename):
  1101. """!Save layer tree layout to workspace file
  1102. Return True on success, False on error
  1103. """
  1104. tmpfile = tempfile.TemporaryFile(mode = 'w+b')
  1105. try:
  1106. WriteWorkspaceFile(lmgr = self, file = tmpfile)
  1107. except StandardError, e:
  1108. GError(parent = self,
  1109. message = _("Writing current settings to workspace file "
  1110. "failed."))
  1111. return False
  1112. try:
  1113. mfile = open(filename, "w")
  1114. tmpfile.seek(0)
  1115. for line in tmpfile.readlines():
  1116. mfile.write(line)
  1117. except IOError:
  1118. GError(parent = self,
  1119. message = _("Unable to open file <%s> for writing.") % filename)
  1120. return False
  1121. mfile.close()
  1122. return True
  1123. def OnWorkspaceClose(self, event = None):
  1124. """!Close file with workspace definition
  1125. If workspace has been modified ask user to save the changes.
  1126. """
  1127. Debug.msg(4, "GMFrame.OnWorkspaceClose(): file=%s" % self.workspaceFile)
  1128. self.OnDisplayCloseAll()
  1129. self.workspaceFile = None
  1130. self.workspaceChanged = False
  1131. self._setTitle()
  1132. self.displayIndex = 0
  1133. self.currentPage = None
  1134. def OnDisplayClose(self, event = None):
  1135. """!Close current map display window
  1136. """
  1137. if self.currentPage and self.GetMapDisplay():
  1138. self.GetMapDisplay().OnCloseWindow(event)
  1139. def OnDisplayCloseAll(self, event = None):
  1140. """!Close all open map display windows
  1141. """
  1142. for display in self.GetMapDisplay(onlyCurrent = False):
  1143. display.OnCloseWindow(event)
  1144. def OnRenameDisplay(self, event):
  1145. """!Change Map Display name"""
  1146. name = self.notebookLayers.GetPageText(self.currentPageNum)
  1147. dlg = wx.TextEntryDialog(self, message = _("Enter new name:"),
  1148. caption = _("Rename Map Display"), defaultValue = name)
  1149. if dlg.ShowModal() == wx.ID_OK:
  1150. name = dlg.GetValue()
  1151. self.notebookLayers.SetPageText(page = self.currentPageNum, text = name)
  1152. mapdisplay = self.GetMapDisplay()
  1153. mapdisplay.SetTitle(_("GRASS GIS Map Display: %(name)s - Location: %(loc)s") % \
  1154. { 'name' : name,
  1155. 'loc' : grass.gisenv()["LOCATION_NAME"] })
  1156. dlg.Destroy()
  1157. def OnRasterRules(self, event):
  1158. """!Launches dialog for raster color rules
  1159. """
  1160. ctable = RasterColorTable(self, layerTree = self.GetLayerTree())
  1161. ctable.Show()
  1162. ctable.CentreOnScreen()
  1163. def OnVectorRules(self, event):
  1164. """!Launches dialog for vector color rules
  1165. """
  1166. ctable = VectorColorTable(self, layerTree = self.GetLayerTree(),
  1167. attributeType = 'color')
  1168. ctable.Show()
  1169. ctable.CentreOnScreen()
  1170. def OnEditImageryGroups(self, event, cmd = None):
  1171. """!Show dialog for creating and editing groups.
  1172. """
  1173. dlg = GroupDialog(self)
  1174. dlg.CentreOnScreen()
  1175. dlg.Show()
  1176. def OnInstallExtension(self, event):
  1177. """!Install extension from GRASS Addons SVN repository"""
  1178. win = InstallExtensionWindow(self, giface=self._giface, size = (650, 550))
  1179. win.CentreOnScreen()
  1180. win.Show()
  1181. def OnManageExtension(self, event):
  1182. """!Uninstall extension"""
  1183. win = ManageExtensionWindow(self, size = (650, 300))
  1184. win.CentreOnScreen()
  1185. win.Show()
  1186. def OnPreferences(self, event):
  1187. """!General GUI preferences/settings
  1188. """
  1189. if not self.dialogs['preferences']:
  1190. dlg = PreferencesDialog(parent = self, giface = self._giface)
  1191. self.dialogs['preferences'] = dlg
  1192. self.dialogs['preferences'].CenterOnScreen()
  1193. dlg.settingsChanged.connect(self.OnSettingsChanged)
  1194. self.dialogs['preferences'].ShowModal()
  1195. def OnNvizPreferences(self, event):
  1196. """!Show nviz preferences"""
  1197. if not self.dialogs['nvizPreferences']:
  1198. dlg = NvizPreferencesDialog(parent = self, giface = self._giface)
  1199. self.dialogs['nvizPreferences'] = dlg
  1200. self.dialogs['nvizPreferences'].CenterOnScreen()
  1201. self.dialogs['nvizPreferences'].Show()
  1202. def OnHelp(self, event):
  1203. """!Show help
  1204. """
  1205. self._gconsole.RunCmd(['g.manual','-i'])
  1206. def OnIClass(self, event=None, cmd=None):
  1207. """!Start wxIClass tool
  1208. The parameters of all handlers which are associated with module
  1209. and contained in menu/toolboxes must be event and cmd.
  1210. When called from menu event is always None and cmd is the associated
  1211. command (list containing a module name and paremeters).
  1212. @todo This documentation is actually documentation of some component related
  1213. to gui_core/menu.py file.
  1214. """
  1215. from iclass.frame import IClassMapFrame, haveIClass, errMsg
  1216. if not haveIClass:
  1217. GError(_('Unable to launch "Supervised Classification Tool".\n\n'
  1218. 'Reason: %s') % errMsg)
  1219. return
  1220. win = IClassMapFrame(parent = self, giface = self._giface)
  1221. win.CentreOnScreen()
  1222. win.Show()
  1223. def OnAnimationTool(self, event):
  1224. """!Launch Animation tool
  1225. """
  1226. from animation.frame import AnimationFrame
  1227. frame = AnimationFrame(parent=self, giface=self._giface)
  1228. frame.CentreOnScreen()
  1229. frame.Show()
  1230. tree = self.GetLayerTree()
  1231. if tree:
  1232. rasters = []
  1233. for layer in tree.GetSelectedLayers(checkedOnly = False):
  1234. if tree.GetLayerInfo(layer, key = 'type') == 'raster':
  1235. rasters.append(tree.GetLayerInfo(layer, key = 'maplayer').GetName())
  1236. if len(rasters) >= 2:
  1237. from core.layerlist import LayerList
  1238. from animation.data import AnimLayer
  1239. layerList = LayerList()
  1240. layer = AnimLayer()
  1241. layer.mapType = 'rast'
  1242. layer.name = ','.join(rasters)
  1243. layer.cmd = ['d.rast', 'map=']
  1244. layerList.AddLayer(layer)
  1245. frame.SetAnimations([layerList, None, None, None])
  1246. def OnHistogram(self, event):
  1247. """!Init histogram display canvas and tools
  1248. """
  1249. from modules.histogram import HistogramFrame
  1250. win = HistogramFrame(self, giface=self._giface)
  1251. win.CentreOnScreen()
  1252. win.Show()
  1253. win.Refresh()
  1254. win.Update()
  1255. def OnMapCalculator(self, event, cmd = ''):
  1256. """!Init map calculator for interactive creation of mapcalc statements
  1257. """
  1258. if event:
  1259. try:
  1260. cmd = self.GetMenuCmd(event)
  1261. except KeyError:
  1262. cmd = ['r.mapcalc']
  1263. win = MapCalcFrame(parent = self,
  1264. giface = self._giface,
  1265. cmd = cmd[0])
  1266. win.CentreOnScreen()
  1267. win.Show()
  1268. def OnVectorCleaning(self, event, cmd = ''):
  1269. """!Init interactive vector cleaning
  1270. """
  1271. from modules.vclean import VectorCleaningFrame
  1272. win = VectorCleaningFrame(parent = self)
  1273. win.CentreOnScreen()
  1274. win.Show()
  1275. def OnRasterOutputFormat(self, event):
  1276. """!Set raster output format handler"""
  1277. self.OnMenuCmd(cmd = ['r.external.out'])
  1278. def OnVectorOutputFormat(self, event):
  1279. """!Set vector output format handler"""
  1280. dlg = GdalOutputDialog(parent = self, ogr = True)
  1281. dlg.CentreOnScreen()
  1282. dlg.Show()
  1283. def OnImportDxfFile(self, event, cmd = None):
  1284. """!Convert multiple DXF layers to GRASS vector map layers"""
  1285. dlg = DxfImportDialog(parent = self, giface = self._giface)
  1286. dlg.CentreOnScreen()
  1287. dlg.Show()
  1288. def OnImportGdalLayers(self, event, cmd = None):
  1289. """!Convert multiple GDAL layers to GRASS raster map layers"""
  1290. dlg = GdalImportDialog(parent = self, giface = self._giface)
  1291. dlg.CentreOnScreen()
  1292. dlg.Show()
  1293. def OnLinkGdalLayers(self, event, cmd = None):
  1294. """!Link multiple GDAL layers to GRASS raster map layers"""
  1295. dlg = GdalImportDialog(parent = self, giface = self._giface, link = True)
  1296. dlg.CentreOnScreen()
  1297. dlg.Show()
  1298. def OnImportOgrLayers(self, event, cmd = None):
  1299. """!Convert multiple OGR layers to GRASS vector map layers"""
  1300. dlg = GdalImportDialog(parent = self, giface = self._giface, ogr = True)
  1301. dlg.CentreOnScreen()
  1302. dlg.Show()
  1303. def OnLinkOgrLayers(self, event, cmd = None):
  1304. """!Links multiple OGR layers to GRASS vector map layers"""
  1305. dlg = GdalImportDialog(parent = self, giface = self._giface, ogr = True, link = True)
  1306. dlg.CentreOnScreen()
  1307. dlg.Show()
  1308. def OnAddWS(self, event, cmd = None):
  1309. """!Add web services layer"""
  1310. from web_services.dialogs import AddWSDialog
  1311. dlg = AddWSDialog(parent = self, giface = self._giface)
  1312. dlg.CentreOnScreen()
  1313. x, y = dlg.GetPosition()
  1314. dlg.SetPosition((x, y - 200))
  1315. dlg.Show()
  1316. def OnShowAttributeTable(self, event, selection = None):
  1317. """!Show attribute table of the given vector map layer
  1318. """
  1319. if not self.currentPage:
  1320. self.MsgNoLayerSelected()
  1321. return
  1322. tree = self.GetLayerTree()
  1323. layer = tree.layer_selected
  1324. # no map layer selected
  1325. if not layer:
  1326. self.MsgNoLayerSelected()
  1327. return
  1328. # available only for vector map layers
  1329. try:
  1330. maptype = tree.GetLayerInfo(layer, key = 'maplayer').type
  1331. except:
  1332. maptype = None
  1333. if not maptype or maptype != 'vector':
  1334. GMessage(parent = self,
  1335. message = _("Selected map layer is not vector."))
  1336. return
  1337. if not tree.GetLayerInfo(layer):
  1338. return
  1339. dcmd = tree.GetLayerInfo(layer, key = 'cmd')
  1340. if not dcmd:
  1341. return
  1342. dbmanager = AttributeManager(parent = self, id = wx.ID_ANY,
  1343. size = wx.Size(500, 300),
  1344. item = layer, log = self._gconsole,
  1345. selection = selection)
  1346. # register ATM dialog
  1347. self.dialogs['atm'].append(dbmanager)
  1348. # show ATM window
  1349. dbmanager.Show()
  1350. def OnNewDisplay(self, event = None):
  1351. """!Create new layer tree and map display instance"""
  1352. self.NewDisplay()
  1353. def NewDisplay(self, name = None, show = True):
  1354. """!Create new layer tree, which will
  1355. create an associated map display frame
  1356. @param name name of new map display
  1357. @param show show map display window if True
  1358. @return reference to mapdisplay intance
  1359. """
  1360. Debug.msg(1, "GMFrame.NewDisplay(): idx=%d" % self.displayIndex)
  1361. # make a new page in the bookcontrol for the layer tree (on page 0 of the notebook)
  1362. self.pg_panel = wx.Panel(self.notebookLayers, id = wx.ID_ANY, style = wx.EXPAND)
  1363. if name:
  1364. dispName = name
  1365. else:
  1366. dispName = "Display " + str(self.displayIndex + 1)
  1367. self.notebookLayers.AddPage(self.pg_panel, text = dispName, select = True)
  1368. self.currentPage = self.notebookLayers.GetCurrentPage()
  1369. # create layer tree (tree control for managing GIS layers) and put on new notebook page
  1370. self.currentPage.maptree = LayerTree(self.currentPage, giface = self._giface,
  1371. id = wx.ID_ANY, pos = wx.DefaultPosition,
  1372. size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
  1373. wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
  1374. wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
  1375. idx = self.displayIndex, lmgr = self, notebook = self.notebookLayers,
  1376. showMapDisplay = show)
  1377. # layout for controls
  1378. cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
  1379. cb_boxsizer.Add(self.GetLayerTree(), proportion = 1, flag = wx.EXPAND, border = 1)
  1380. self.currentPage.SetSizer(cb_boxsizer)
  1381. cb_boxsizer.Fit(self.GetLayerTree())
  1382. self.currentPage.Layout()
  1383. self.GetLayerTree().Layout()
  1384. mapdisplay = self.currentPage.maptree.mapdisplay
  1385. mapdisplay.Bind(wx.EVT_ACTIVATE,
  1386. lambda event, page=self.currentPage:
  1387. self._onMapDisplayFocus(page))
  1388. mapdisplay.starting3dMode.connect(
  1389. lambda firstTime, mapDisplayPage=self.currentPage:
  1390. self._onMapDisplayStarting3dMode(mapDisplayPage))
  1391. mapdisplay.starting3dMode.connect(self.AddNvizTools)
  1392. mapdisplay.ending3dMode.connect(self.RemoveNvizTools)
  1393. # use default window layout
  1394. if UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'enabled'):
  1395. dim = UserSettings.Get(group = 'general', key = 'defWindowPos', subkey = 'dim')
  1396. idx = 4 + self.displayIndex * 4
  1397. try:
  1398. x, y = map(int, dim.split(',')[idx:idx + 2])
  1399. w, h = map(int, dim.split(',')[idx + 2:idx + 4])
  1400. self.GetMapDisplay().SetPosition((x, y))
  1401. self.GetMapDisplay().SetSize((w, h))
  1402. except:
  1403. pass
  1404. self.displayIndex += 1
  1405. return self.GetMapDisplay()
  1406. def _onMapDisplayFocus(self, notebookLayerPage):
  1407. """Changes bookcontrol page to page associated with display."""
  1408. # moved from mapdisp/frame.py
  1409. # TODO: why it is called 3 times when getting focus?
  1410. # and one times when loosing focus?
  1411. pgnum = self.notebookLayers.GetPageIndex(notebookLayerPage)
  1412. if pgnum > -1:
  1413. self.notebookLayers.SetSelection(pgnum)
  1414. self.currentPage = self.notebookLayers.GetCurrentPage()
  1415. def _onMapDisplayStarting3dMode(self, mapDisplayPage):
  1416. """!Disables 3D mode for all map displays except for @p mapDisplay"""
  1417. # TODO: it should be disabled also for newly created map windows
  1418. # moreover mapdisp.Disable3dMode() does not work properly
  1419. for page in range(0, self.GetLayerNotebook().GetPageCount()):
  1420. mapdisp = self.GetLayerNotebook().GetPage(page).maptree.GetMapDisplay()
  1421. if self.GetLayerNotebook().GetPage(page) != mapDisplayPage:
  1422. mapdisp.Disable3dMode()
  1423. def OnAddMaps(self, event = None):
  1424. """!Add selected map layers into layer tree"""
  1425. dialog = MapLayersDialog(parent = self, title = _("Add selected map layers into layer tree"))
  1426. dialog.applyAddingMapLayers.connect(self.AddMaps)
  1427. val = dialog.ShowModal()
  1428. if val == wx.ID_OK:
  1429. self.AddMaps(dialog.GetMapLayers(), dialog.GetLayerType(cmd = True))
  1430. dialog.Destroy()
  1431. def AddMaps(self, mapLayers, ltype, check = False):
  1432. """!Add map layers to layer tree.
  1433. @param mapLayers list of map names
  1434. @param ltype layer type ('rast', 'rast3d', 'vect')
  1435. @param check @c True if new layers should be checked in layer tree
  1436. @c False otherwise
  1437. """
  1438. # start new map display if no display is available
  1439. if not self.currentPage:
  1440. self.NewDisplay()
  1441. maptree = self.GetLayerTree()
  1442. for layerName in mapLayers:
  1443. if ltype == 'rast':
  1444. cmd = ['d.rast', 'map=%s' % layerName]
  1445. wxType = 'raster'
  1446. elif ltype == 'rast3d':
  1447. cmd = ['d.rast3d', 'map=%s' % layerName]
  1448. wxType = '3d-raster'
  1449. elif ltype == 'vect':
  1450. cmd = ['d.vect', 'map=%s' % layerName] + GetDisplayVectSettings()
  1451. wxType = 'vector'
  1452. else:
  1453. GError(parent = self,
  1454. message = _("Unsupported map layer type <%s>.") % ltype)
  1455. return
  1456. newItem = maptree.AddLayer(ltype = wxType,
  1457. lname = layerName,
  1458. lchecked = check,
  1459. lopacity = 1.0,
  1460. lcmd = cmd,
  1461. lgroup = None)
  1462. def _updateCurrentMap(self):
  1463. """!Updates map of the current map window."""
  1464. self.GetMapDisplay().GetWindow().UpdateMap()
  1465. def OnMapCreated(self, name, ltype, add=None):
  1466. """!Decides wheter the map should be added to layer tree."""
  1467. if add is None:
  1468. # add new map into layer if globally enabled
  1469. if UserSettings.Get(group = 'cmd',
  1470. key = 'addNewLayer', subkey = 'enabled'):
  1471. self.AddOrUpdateMap(name, ltype)
  1472. elif add:
  1473. # add new map into layer tree
  1474. self.AddOrUpdateMap(name, ltype)
  1475. else:
  1476. # update the map
  1477. display = self.GetMapDisplay()
  1478. display.GetWindow().UpdateMap(render = True)
  1479. def AddOrUpdateMap(self, mapName, ltype):
  1480. """!Add map layer or update"""
  1481. # start new map display if no display is available
  1482. # TODO: standardize type identifiers
  1483. convertType = {'raster': 'rast',
  1484. '3d-raster': 'rast3d',
  1485. 'vector': 'vect'}
  1486. try:
  1487. grassType = convertType[ltype]
  1488. except KeyError:
  1489. if ltype in convertType.values():
  1490. grassType = ltype
  1491. else:
  1492. GError(parent = self,
  1493. message = _("Unsupported map layer type <%s>.") % ltype)
  1494. return
  1495. if not self.currentPage:
  1496. self.AddMaps([mapName], grassType, check = True)
  1497. else:
  1498. display = self.GetMapDisplay()
  1499. mapLayers = map(lambda x: x.GetName(),
  1500. display.GetMap().GetListOfLayers(ltype = ltype))
  1501. if mapName in mapLayers:
  1502. display.GetWindow().UpdateMap(render = True)
  1503. else:
  1504. self.AddMaps([mapName], grassType, check = True)
  1505. def OnAddRaster(self, event):
  1506. """!Add raster map layer"""
  1507. # start new map display if no display is available
  1508. if not self.currentPage:
  1509. self.NewDisplay(show = True)
  1510. self.notebook.SetSelectionByName('layers')
  1511. self.GetLayerTree().AddLayer('raster')
  1512. def OnAddRasterMisc(self, event):
  1513. """!Create misc raster popup-menu"""
  1514. # start new map display if no display is available
  1515. if not self.currentPage:
  1516. self.NewDisplay(show = True)
  1517. self._popupMenu((('layer3d-raster', self.OnAddRaster3D),
  1518. (None, None),
  1519. ('layerRgb', self.OnAddRasterRGB),
  1520. ('layerHis', self.OnAddRasterHIS),
  1521. (None, None),
  1522. ('layerShaded', self.OnAddRasterShaded),
  1523. (None, None),
  1524. ('layerRastarrow', self.OnAddRasterArrow),
  1525. ('layerRastnum', self.OnAddRasterNum)))
  1526. # show map display
  1527. self.GetMapDisplay().Show()
  1528. def OnAddVector(self, event):
  1529. """!Add vector map to the current layer tree"""
  1530. # start new map display if no display is available
  1531. if not self.currentPage:
  1532. self.NewDisplay(show = True)
  1533. self.notebook.SetSelectionByName('layers')
  1534. self.GetLayerTree().AddLayer('vector')
  1535. def OnAddVectorMisc(self, event):
  1536. """!Create misc vector popup-menu"""
  1537. # start new map display if no display is available
  1538. if not self.currentPage:
  1539. self.NewDisplay(show = True)
  1540. self._popupMenu((('layerThememap', self.OnAddVectorTheme),
  1541. ('layerThemechart', self.OnAddVectorChart)))
  1542. # show map display
  1543. self.GetMapDisplay().Show()
  1544. def OnAddVectorTheme(self, event):
  1545. """!Add thematic vector map to the current layer tree"""
  1546. self.notebook.SetSelectionByName('layers')
  1547. self.GetLayerTree().AddLayer('thememap')
  1548. def OnAddVectorChart(self, event):
  1549. """!Add chart vector map to the current layer tree"""
  1550. self.notebook.SetSelectionByName('layers')
  1551. self.GetLayerTree().AddLayer('themechart')
  1552. def OnAddOverlay(self, event):
  1553. """!Create decoration overlay menu"""
  1554. # start new map display if no display is available
  1555. if not self.currentPage:
  1556. self.NewDisplay(show = True)
  1557. self._popupMenu((('layerGrid', self.OnAddGrid),
  1558. ('layerLabels', self.OnAddLabels),
  1559. ('layerGeodesic', self.OnAddGeodesic),
  1560. ('layerRhumb', self.OnAddRhumb),
  1561. (None, None),
  1562. ('layerCmd', self.OnAddCommand)))
  1563. # show map display
  1564. self.GetMapDisplay().Show()
  1565. def OnAddRaster3D(self, event):
  1566. """!Add 3D raster map to the current layer tree"""
  1567. self.notebook.SetSelectionByName('layers')
  1568. self.GetLayerTree().AddLayer('3d-raster')
  1569. def OnAddRasterRGB(self, event):
  1570. """!Add RGB raster map to the current layer tree"""
  1571. self.notebook.SetSelectionByName('layers')
  1572. self.GetLayerTree().AddLayer('rgb')
  1573. def OnAddRasterHIS(self, event):
  1574. """!Add HIS raster map to the current layer tree"""
  1575. self.notebook.SetSelectionByName('layers')
  1576. self.GetLayerTree().AddLayer('his')
  1577. def OnAddRasterShaded(self, event):
  1578. """!Add shaded relief raster map to the current layer tree"""
  1579. self.notebook.SetSelectionByName('layers')
  1580. self.GetLayerTree().AddLayer('shaded')
  1581. def OnAddRasterArrow(self, event):
  1582. """!Add flow arrows raster map to the current layer tree"""
  1583. self.notebook.SetSelectionByName('layers')
  1584. # here it seems that it should be retrieved from the mapwindow
  1585. mapdisplay = self.GetMapDisplay()
  1586. resolution = mapdisplay.mapWindowProperties.resolution
  1587. if not resolution:
  1588. dlg = self.MsgDisplayResolution()
  1589. if dlg.ShowModal() == wx.ID_YES:
  1590. mapdisplay.mapWindowProperties.resolution = True
  1591. dlg.Destroy()
  1592. self.GetLayerTree().AddLayer('rastarrow')
  1593. def OnAddRasterNum(self, event):
  1594. """!Add cell number raster map to the current layer tree"""
  1595. self.notebook.SetSelectionByName('layers')
  1596. mapdisplay = self.GetMapDisplay()
  1597. resolution = mapdisplay.mapWindowProperties.resolution
  1598. if not resolution:
  1599. limitText = _("Note that cell values can only be displayed for "
  1600. "regions of less than 10,000 cells.")
  1601. dlg = self.MsgDisplayResolution(limitText)
  1602. if dlg.ShowModal() == wx.ID_YES:
  1603. mapdisplay.mapWindowProperties.resolution = True
  1604. dlg.Destroy()
  1605. # region = tree.GetMap().GetCurrentRegion()
  1606. # if region['cells'] > 10000:
  1607. # GMessage(message = "Cell values can only be displayed for regions of < 10,000 cells.", parent = self)
  1608. self.GetLayerTree().AddLayer('rastnum')
  1609. def OnAddCommand(self, event):
  1610. """!Add command line map layer to the current layer tree"""
  1611. # start new map display if no display is available
  1612. if not self.currentPage:
  1613. self.NewDisplay(show = True)
  1614. self.notebook.SetSelectionByName('layers')
  1615. self.GetLayerTree().AddLayer('command')
  1616. # show map display
  1617. self.GetMapDisplay().Show()
  1618. def OnAddGroup(self, event):
  1619. """!Add layer group"""
  1620. # start new map display if no display is available
  1621. if not self.currentPage:
  1622. self.NewDisplay(show = True)
  1623. self.notebook.SetSelectionByName('layers')
  1624. self.GetLayerTree().AddLayer('group')
  1625. # show map display
  1626. self.GetMapDisplay().Show()
  1627. def OnAddGrid(self, event):
  1628. """!Add grid map layer to the current layer tree"""
  1629. self.notebook.SetSelectionByName('layers')
  1630. self.GetLayerTree().AddLayer('grid')
  1631. def OnAddGeodesic(self, event):
  1632. """!Add geodesic line map layer to the current layer tree"""
  1633. self.notebook.SetSelectionByName('layers')
  1634. self.GetLayerTree().AddLayer('geodesic')
  1635. def OnAddRhumb(self, event):
  1636. """!Add rhumb map layer to the current layer tree"""
  1637. self.notebook.SetSelectionByName('layers')
  1638. self.GetLayerTree().AddLayer('rhumb')
  1639. def OnAddLabels(self, event):
  1640. """!Add vector labels map layer to the current layer tree"""
  1641. # start new map display if no display is available
  1642. if not self.currentPage:
  1643. self.NewDisplay(show = True)
  1644. self.notebook.SetSelectionByName('layers')
  1645. self.GetLayerTree().AddLayer('labels')
  1646. # show map display
  1647. self.GetMapDisplay().Show()
  1648. def OnDeleteLayer(self, event):
  1649. """!Remove selected map layer from the current layer Tree
  1650. """
  1651. if not self.currentPage or not self.GetLayerTree().layer_selected:
  1652. self.MsgNoLayerSelected()
  1653. return
  1654. if UserSettings.Get(group = 'manager', key = 'askOnRemoveLayer', subkey = 'enabled'):
  1655. layerName = ''
  1656. for item in self.GetLayerTree().GetSelections():
  1657. name = str(self.GetLayerTree().GetItemText(item))
  1658. idx = name.find('(opacity')
  1659. if idx > -1:
  1660. layerName += '<' + name[:idx].strip(' ') + '>,\n'
  1661. else:
  1662. layerName += '<' + name + '>,\n'
  1663. layerName = layerName.rstrip(',\n')
  1664. if len(layerName) > 2: # <>
  1665. message = _("Do you want to remove map layer(s)\n%s\n"
  1666. "from layer tree?") % layerName
  1667. else:
  1668. message = _("Do you want to remove selected map layer(s) "
  1669. "from layer tree?")
  1670. dlg = wx.MessageDialog (parent = self, message = message,
  1671. caption = _("Remove map layer"),
  1672. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
  1673. if dlg.ShowModal() != wx.ID_YES:
  1674. dlg.Destroy()
  1675. return
  1676. dlg.Destroy()
  1677. for layer in self.GetLayerTree().GetSelections():
  1678. if self.GetLayerTree().GetLayerInfo(layer, key = 'type') == 'group':
  1679. self.GetLayerTree().DeleteChildren(layer)
  1680. self.GetLayerTree().Delete(layer)
  1681. def OnKeyDown(self, event):
  1682. """!Key pressed"""
  1683. kc = event.GetKeyCode()
  1684. if event.ControlDown():
  1685. if kc == wx.WXK_TAB:
  1686. # switch layer list / command output
  1687. if self.notebook.GetSelection() == self.notebook.GetPageIndexByName('layers'):
  1688. self.notebook.SetSelectionByName('output')
  1689. else:
  1690. self.notebook.SetSelectionByName('layers')
  1691. try:
  1692. ckc = chr(kc)
  1693. except ValueError:
  1694. event.Skip()
  1695. return
  1696. if event.CtrlDown():
  1697. if kc == 'R':
  1698. self.OnAddRaster(None)
  1699. elif kc == 'V':
  1700. self.OnAddVector(None)
  1701. event.Skip()
  1702. def OnCloseWindow(self, event):
  1703. """!Cleanup when wxGUI is quitted"""
  1704. # save command protocol if actived
  1705. if self.goutput.btnCmdProtocol.GetValue():
  1706. self.goutput.CmdProtocolSave()
  1707. if not self.currentPage:
  1708. self._auimgr.UnInit()
  1709. self.Destroy()
  1710. return
  1711. # save changes in the workspace
  1712. maptree = self.GetLayerTree()
  1713. if self.workspaceChanged and \
  1714. UserSettings.Get(group = 'manager', key = 'askOnQuit', subkey = 'enabled'):
  1715. if self.workspaceFile:
  1716. message = _("Do you want to save changes in the workspace?")
  1717. else:
  1718. message = _("Do you want to store current settings "
  1719. "to workspace file?")
  1720. # ask user to save current settings
  1721. if maptree.GetCount() > 0:
  1722. dlg = wx.MessageDialog(self,
  1723. message = message,
  1724. caption = _("Quit GRASS GUI"),
  1725. style = wx.YES_NO | wx.YES_DEFAULT |
  1726. wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
  1727. ret = dlg.ShowModal()
  1728. if ret == wx.ID_YES:
  1729. if not self.workspaceFile:
  1730. self.OnWorkspaceSaveAs()
  1731. else:
  1732. self.SaveToWorkspaceFile(self.workspaceFile)
  1733. elif ret == wx.ID_CANCEL:
  1734. # when called from menu, it gets CommandEvent and not CloseEvent
  1735. if hasattr(event, 'Veto'):
  1736. event.Veto()
  1737. dlg.Destroy()
  1738. return
  1739. dlg.Destroy()
  1740. # don't ask any more...
  1741. UserSettings.Set(group = 'manager', key = 'askOnQuit', subkey = 'enabled',
  1742. value = False)
  1743. self.OnDisplayCloseAll()
  1744. self.notebookLayers.DeleteAllPages()
  1745. self._auimgr.UnInit()
  1746. self.Destroy()
  1747. def MsgNoLayerSelected(self):
  1748. """!Show dialog message 'No layer selected'"""
  1749. wx.MessageBox(parent = self,
  1750. message = _("No map layer selected. Operation canceled."),
  1751. caption = _("Message"),
  1752. style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
  1753. def MsgDisplayResolution(self, limitText = None):
  1754. """!Returns dialog for d.rast.num, d.rast.arrow
  1755. when display resolution is not constrained
  1756. @param limitText adds a note about cell limit
  1757. """
  1758. message = _("Display resolution is currently not constrained to "
  1759. "computational settings. "
  1760. "It's suggested to constrain map to region geometry. "
  1761. "Do you want to constrain "
  1762. "the resolution?")
  1763. if limitText:
  1764. message += "\n\n%s" % _(limitText)
  1765. dlg = wx.MessageDialog(parent = self,
  1766. message = message,
  1767. caption = _("Constrain map to region geometry?"),
  1768. style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
  1769. return dlg