frame.py 92 KB

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