frame.py 79 KB

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