frame.py 85 KB

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