frame.py 93 KB

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