frame.py 96 KB

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