frame.py 83 KB

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