4 @brief Layer Manager - main menu, layer management toolbar, notebook
5 control for display management and access to command console.
10 (C) 2006-2014 by the GRASS Development Team
12 This program is free software under the GNU General Public License
13 (>=v2). Read the file COPYING that comes with GRASS for details.
15 @author Michael Barton (Arizona State University)
16 @author Jachym Cepicky (Mendel University of Agriculture)
17 @author Martin Landa <landa.martin gmail.com>
18 @author Vaclav Petras <wenzeslaus gmail.com> (menu customization)
27 import xml.etree.ElementTree
as etree
29 import elementtree.ElementTree
as etree
31 from core
import globalvar
35 import wx.lib.agw.flatnotebook
as FN
37 import wx.lib.flatnotebook
as FN
39 sys.path.append(os.path.join(globalvar.ETCDIR,
"python"))
42 from core.gcmd import Command, RunCommand, GError, GMessage
47 from lmgr.menudata
import ManagerData
49 from modules.mcalc_builder
import MapCalcFrame
51 from core.workspace import ProcessWorkspaceFile, ProcessGrcFile, WriteWorkspaceFile
53 from gui_core.dialogs import DxfImportDialog, GdalImportDialog, MapLayersDialog
54 from gui_core.dialogs import LocationDialog, MapsetDialog, CreateNewVector, GroupDialog
55 from modules.ogc_services
import WMSDialog
56 from modules.colorrules
import RasterColorTable, VectorColorTable
64 from lmgr.toolbars import LMWorkspaceToolbar, LMDataToolbar, LMToolsToolbar
65 from lmgr.toolbars import LMMiscToolbar, LMVectorToolbar, LMNvizToolbar
67 from gui_core.forms
import GUI
72 """!Layer Manager frame with notebook widget for controlling GRASS
73 GIS. Includes command console page for typing GRASS (and other)
74 commands, tree widget page for managing map layers.
76 def __init__(self, parent, id = wx.ID_ANY, title = None,
78 size = globalvar.GM_WINDOW_SIZE, style = wx.DEFAULT_FRAME_STYLE, **kwargs):
83 self.
baseTitle = _(
"GRASS GIS %s Layer Manager") % grass.version()[
'version']
86 wx.Frame.__init__(self, parent = parent, id = id, size = size,
87 style = style, **kwargs)
89 self.SetName(
"LayerManager")
91 self.SetIcon(wx.Icon(os.path.join(globalvar.ETCICONDIR,
'grass.ico'), wx.BITMAP_TYPE_ICO))
93 self.
_auimgr = wx.aui.AuiManager(self)
106 self.
dialogs[
'preferences'] =
None
113 self.
toolbars = {
'workspace' : LMWorkspaceToolbar(parent = self),
114 'data' : LMDataToolbar(parent = self),
115 'tools' : LMToolsToolbar(parent = self),
116 'misc' : LMMiscToolbar(parent = self),
117 'vector' : LMVectorToolbar(parent = self),
118 'nviz' : LMNvizToolbar(parent = self)}
121 _(
"Workspace Toolbar"),
123 'data' : (
"toolbarData",
126 'misc' : (
"toolbarMisc",
129 'tools' : (
"toolbarTools",
132 'vector' : (
"toolbarVector",
135 'nviz' : (
"toolbarNviz",
136 _(
"3D view Toolbar"),
139 if sys.platform ==
'win32':
141 'vector',
'tools',
'misc',
'nviz')
144 'nviz',
'misc',
'tools',
'vector')
147 self._auimgr.AddPane(self.
toolbars[toolbar],
148 wx.aui.AuiPaneInfo().
149 Name(name).Caption(caption).
150 ToolbarPane().Top().Row(row).
151 LeftDockable(
False).RightDockable(
False).
152 BottomDockable(
False).TopDockable(
True).
153 CloseButton(
False).Layer(2).
154 BestSize((self.
toolbars[toolbar].GetBestSize())))
156 self._auimgr.GetPane(
'toolbarNviz').Hide()
159 self.Bind(wx.EVT_KEY_DOWN, self.
OnKeyDown)
162 self.SetMinSize((globalvar.GM_WINDOW_SIZE[0], 400))
165 self._auimgr.AddPane(self.
notebook, wx.aui.AuiPaneInfo().
166 Left().CentrePane().BestSize((-1,-1)).Dockable(
False).
167 CloseButton(
False).DestroyOnClose(
True).Row(1).Layer(0))
169 self._auimgr.Update()
171 wx.CallAfter(self.notebook.SetSelectionByName,
'layers')
174 if UserSettings.Get(group =
'general', key =
'defWindowPos', subkey =
'enabled'):
175 dim = UserSettings.Get(group =
'general', key =
'defWindowPos', subkey =
'dim')
177 x, y = map(int, dim.split(
',')[0:2])
178 w, h = map(int, dim.split(
',')[2:4])
179 self.SetPosition((x, y))
206 self.goutput.Redirect()
209 self.goutput.SetSashPosition(int(self.GetSize()[1] * .8))
216 wx.CallAfter(self.Raise)
218 def _createMenuBar(self):
219 """!Creates menu bar"""
220 self.
menubar = Menu(parent = self, data = ManagerData())
224 def _createTabMenu(self):
225 """!Creates context menu for display tabs.
227 Used to rename display.
230 item = wx.MenuItem(menu, id = wx.ID_ANY, text = _(
"Rename Map Display"))
231 menu.AppendItem(item)
236 def _setCopyingOfSelectedText(self):
237 copy = UserSettings.Get(group =
'manager', key =
'copySelectedTextToClipboard', subkey =
'enabled')
238 self.goutput.SetCopyingOfSelectedText(copy)
241 """!Check if pane (toolbar, ...) of given name is currently shown"""
242 if self._auimgr.GetPane(name).IsOk():
243 return self._auimgr.GetPane(name).IsShown()
246 def _createNoteBook(self):
247 """!Creates notebook widgets"""
248 self.
notebook = GNotebook(parent = self, style = globalvar.FNPageDStyle)
250 cbStyle = globalvar.FNPageStyle
254 self.
notebookLayers = FN.FlatNotebook(self, id = wx.ID_ANY, style = cbStyle)
255 self.notebookLayers.SetTabAreaColour(globalvar.FNPageColor)
257 self.notebookLayers.SetRightClickMenu(menu)
258 self.notebook.AddPage(page = self.
notebookLayers, text = _(
"Map layers"), name =
'layers')
262 self.notebook.AddPage(page = self.
goutput, text = _(
"Command console"), name =
'output')
266 if not UserSettings.Get(group =
'manager', key =
'hideTabs', subkey =
'search'):
267 self.
search = MenuTreeWindow(parent = self)
268 self.notebook.AddPage(page = self.
search, text = _(
"Search module"), name =
'search')
273 if not UserSettings.Get(group =
'manager', key =
'hideTabs', subkey =
'pyshell'):
275 self.notebook.AddPage(page = self.
pyshell, text = _(
"Python shell"), name =
'pyshell')
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)
287 """!Add nviz notebook page"""
288 Debug.msg(5,
"GMFrame.AddNvizTools()")
295 self._auimgr.GetPane(
'toolbarNviz').Show()
297 for pos, toolbar
in enumerate((
'toolbarVector',
'toolbarTools',
'toolbarMisc',
'toolbarNviz')):
298 self._auimgr.GetPane(toolbar).Row(2).Position(pos)
299 self._auimgr.Update()
304 idx = self.notebook.GetPageIndexByName(
'layers')
305 self.notebook.InsertPage(indx = idx + 1, page = self.
nviz, text = _(
"3D view"), name =
'nviz')
306 self.notebook.SetSelectionByName(
'nviz')
310 """!Remove nviz notebook page"""
312 self.notebook.SetSelectionByName(
'layers')
313 self.notebook.DeletePage(self.notebook.GetPageIndexByName(
'nviz'))
316 self._auimgr.GetPane(
'toolbarNviz').Hide()
317 for pos, toolbar
in enumerate((
'toolbarVector',
'toolbarTools',
'toolbarMisc')):
318 self._auimgr.GetPane(toolbar).Row(2).Position(pos)
319 self._auimgr.Update()
322 """!Update window title"""
330 """!Launch location wizard"""
334 gWizard = LocationWizard(parent = self,
335 grassdatabase = grass.gisenv()[
'GISDBASE'])
336 location = gWizard.location
339 dlg = wx.MessageDialog(parent = self,
340 message = _(
'Location <%s> created.\n\n'
341 'Do you want to switch to the '
342 'new location?') % location,
343 caption=_(
"Switch to new location?"),
344 style = wx.YES_NO | wx.NO_DEFAULT |
345 wx.ICON_QUESTION | wx.CENTRE)
347 ret = dlg.ShowModal()
352 mapset =
'PERMANENT') != 0:
355 GMessage(parent = self,
356 message = _(
"Current location is <%(loc)s>.\n"
357 "Current mapset is <%(mapset)s>.") % \
358 {
'loc' : location,
'mapset' :
'PERMANENT' })
361 dlg = wx.MessageDialog(parent = self,
362 message = _(
"Do you want to set the default "
363 "region extents and resolution now?"),
364 caption = _(
"Location <%s> created") % location,
365 style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
367 if dlg.ShowModal() == wx.ID_YES:
369 defineRegion = RegionDef(self, location = location)
370 defineRegion.CenterOnScreen()
371 defineRegion.ShowModal()
372 defineRegion.Destroy()
377 """!Here can be functions which have to be called after EVT_SETTINGS_CHANGED.
378 Now only set copying of selected text to clipboard (in goutput).
384 """!Launch georectifier module
389 """!Launch Graphical Modeler"""
396 """!Launch Cartographic Composer
404 """Command execution finished"""
405 if hasattr(self,
"model"):
406 self.model.DeleteIntermediateData(log = self.
goutput)
408 self.SetStatusText(
'')
413 dlg = wx.FileDialog(parent = self, message =_(
"Choose model to run"),
414 defaultDir = os.getcwd(),
415 wildcard = _(
"GRASS Model File (*.gxm)|*.gxm"))
416 if dlg.ShowModal() == wx.ID_OK:
417 filename = dlg.GetPath()
424 self.model.LoadModel(filename)
425 self.model.Run(log = self.
goutput, onDone = self.
OnDone, parent = self)
430 """!Launch mapset access dialog
432 dlg = MapsetAccess(parent = self, id = wx.ID_ANY)
435 if dlg.ShowModal() == wx.ID_OK:
436 ms = dlg.GetMapsets()
439 mapset =
'%s' %
','.join(ms))
442 """!Page in notebook (display) changed"""
443 self.
currentPage = self.notebookLayers.GetCurrentPage()
454 """!Page in notebook changed"""
455 page = event.GetSelection()
456 if page == self.notebook.GetPageIndexByName(
'output'):
458 self.notebook.SetPageText(page, _(
"Command console"))
459 wx.CallAfter(self.goutput.ResetFocus)
460 self.SetStatusText(
'', 0)
465 """!Page of notebook closed
466 Also close associated map display
468 if UserSettings.Get(group =
'manager', key =
'askOnQuit', subkey =
'enabled'):
472 message = _(
"Do you want to save changes in the workspace?")
474 message = _(
"Do you want to store current settings "
475 "to workspace file?")
478 if maptree.GetCount() > 0:
480 dlg = wx.MessageDialog(self,
482 caption = _(
"Close Map Display %s") % name,
483 style = wx.YES_NO | wx.YES_DEFAULT |
484 wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
485 ret = dlg.ShowModal()
491 elif ret == wx.ID_CANCEL:
497 self.notebookLayers.GetPage(event.GetSelection()).maptree.Map.Clean()
498 self.notebookLayers.GetPage(event.GetSelection()).maptree.Close(
True)
505 """!Get Layers Notebook"""
509 """!Get current layer tree
511 @return LayerTree instance
512 @return None no layer tree selected
515 return self.currentPage.maptree
519 """!Get current map display
521 @param onlyCurrent True to return only active mapdisplay
522 False for list of all mapdisplays
524 @return MapFrame instance (or list)
525 @return None no mapdisplay selected
534 for idx
in range(0, self.notebookLayers.GetPageCount()):
535 mlist.append(self.notebookLayers.GetPage(idx).maptree.GetMapDisplay())
542 """!Get widget for command output"""
546 """!Get GRASS command from menu item
548 Return command as a list"""
552 cmd = self.
menucmd[event.GetId()]
557 cmdlist = cmd.split(
' ')
563 if cmd
in [
'vcolors',
'r.mapcalc',
'r3.mapcalc']:
568 name = self.
GetLayerTree().GetPyData(layer)[0][
'maplayer'].name
573 if layer
and len(cmdlist) == 1:
574 if (type ==
'raster' and cmdlist[0][0] ==
'r' and cmdlist[0][1] != '3') or \
575 (type == 'vector' and cmdlist[0][0] == 'v'):
576 input = GUI().GetCommandInputMapParamKey(cmdlist[0])
578 cmdlist.append(
"%s=%s" % (input, name))
583 """!Run command selected from menu"""
586 self.goutput.RunCmd(cmd, switchPage =
False)
589 """!Parse command selected from menu"""
592 GUI(parent = self).ParseCommand(cmd)
595 """!Start vector digitizer
602 layer = tree.layer_selected
610 mapLayer = tree.GetPyData(layer)[0][
'maplayer']
614 if not mapLayer
or mapLayer.GetType() !=
'vector':
615 GMessage(parent = self,
616 message = _(
"Selected map layer is not vector."))
619 if mapLayer.GetMapset() != grass.gisenv()[
'MAPSET']:
620 GMessage(parent = self,
621 message = _(
"Editing is allowed only for vector maps from the "
625 if not tree.GetPyData(layer)[0]:
627 dcmd = tree.GetPyData(layer)[0][
'cmd']
631 tree.OnStartEditing(
None)
636 dlg = wx.FileDialog(parent = self, message = _(
"Choose script file to run"),
637 defaultDir = os.getcwd(),
638 wildcard = _(
"Python script (*.py)|*.py|Bash script (*.sh)|*.sh"))
641 if dlg.ShowModal() == wx.ID_OK:
642 filename = dlg.GetPath()
647 if not os.path.exists(filename):
648 GError(parent = self,
649 message = _(
"Script file '%s' doesn't exist. "
650 "Operation canceled.") % filename)
654 if not os.access(filename, os.X_OK):
655 dlg = wx.MessageDialog(self,
656 message = _(
"Script <%s> is not executable. "
657 "Do you want to set the permissions "
658 "that allows you to run this script "
659 "(note that you must be the owner of the file)?" % \
660 os.path.basename(filename)),
661 caption = _(
"Set permission?"),
662 style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
663 if dlg.ShowModal() != wx.ID_YES:
667 mode = stat.S_IMODE(os.lstat(filename)[stat.ST_MODE])
668 os.chmod(filename, mode | stat.S_IXUSR)
670 GError(_(
"Unable to set permission. Operation canceled."), parent = self)
674 addonPath = os.getenv(
'GRASS_ADDON_PATH', [])
676 addonPath = addonPath.split(os.pathsep)
677 dirName = os.path.dirname(filename)
678 if dirName
not in addonPath:
679 addonPath.append(dirName)
680 dlg = wx.MessageDialog(self,
681 message = _(
"Directory '%s' is not defined in GRASS_ADDON_PATH. "
682 "Do you want add this directory to GRASS_ADDON_PATH?") % \
684 caption = _(
"Update Addons path?"),
685 style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
686 if dlg.ShowModal() == wx.ID_YES:
689 self.goutput.WriteCmdLog(_(
"Launching script '%s'...") % filename)
690 self.goutput.RunCmd([filename], switchPage =
True)
693 """Change current location"""
694 dlg = LocationDialog(parent = self)
695 if dlg.ShowModal() == wx.ID_OK:
696 location, mapset = dlg.GetValues()
699 if not location
or not mapset:
700 GError(parent = self,
701 message = _(
"No location/mapset provided. Operation canceled."))
706 mapset = mapset) != 0:
712 GMessage(parent = self,
713 message = _(
"Current location is <%(loc)s>.\n"
714 "Current mapset is <%(mapset)s>.") % \
715 {
'loc' : location,
'mapset' : mapset })
718 """!Create new mapset"""
719 dlg = wx.TextEntryDialog(parent = self,
720 message = _(
'Enter name for new mapset:'),
721 caption = _(
'Create new mapset'))
723 if dlg.ShowModal() == wx.ID_OK:
724 mapset = dlg.GetValue()
726 GError(parent = self,
727 message = _(
"No mapset provided. Operation canceled."))
735 GMessage(parent = self,
736 message = _(
"Current mapset is <%s>.") % mapset)
739 """Change current mapset"""
740 dlg = MapsetDialog(parent = self)
742 if dlg.ShowModal() == wx.ID_OK:
743 mapset = dlg.GetMapset()
747 GError(parent = self,
748 message = _(
"No mapset provided. Operation canceled."))
753 mapset = mapset) == 0:
754 GMessage(parent = self,
755 message = _(
"Current mapset is <%s>.") % mapset)
758 """!Create new vector map layer"""
761 {
'tool' :
'create' },
767 name = dlg.GetName(full =
True)
768 if name
and dlg.IsChecked(
'add'):
772 lcmd = [
'd.vect',
'map=%s' % name])
776 """!Print system information"""
777 vInfo = grass.version()
781 from osgeo
import gdal
782 gdalVersion = gdal.__version__
785 gdalVersion = grass.Popen([
'gdalinfo',
'--version'], stdout = grass.PIPE).communicate()[0].rstrip(
'\n')
787 gdalVersion = _(
"unknown")
790 projVersion =
RunCommand(
'proj', getErrorMsg =
True)[1].splitlines()[0]
792 projVersion = _(
"unknown")
794 if sys.platform ==
'win32' and \
795 not os.path.exists(os.path.join(os.getenv(
"GISBASE"),
"WinGRASS-README.url")):
796 osgeo4w =
' (OSGeo4W)'
800 self.goutput.WriteCmdLog(_(
"System Info"))
801 self.goutput.WriteLog(
"%s: %s\n"
808 "%s: %s%s\n"% (_(
"GRASS version"), vInfo[
'version'],
809 _(
"GRASS SVN Revision"), vInfo[
'revision'],
811 gdalVersion, projVersion,
812 platform.python_version(),
814 _(
"Platform"), platform.platform(), osgeo4w),
816 self.goutput.WriteCmdLog(
' ')
819 """!Display 'About GRASS' dialog"""
820 win = AboutWindow(self)
824 def _popupMenu(self, data):
825 """!Create popup menu
827 point = wx.GetMousePosition()
830 for key, handler
in data:
832 menu.AppendSeparator()
834 item = wx.MenuItem(menu, wx.ID_ANY, LMIcons[key].GetLabel())
835 item.SetBitmap(LMIcons[key].GetBitmap(self.
iconsize))
836 menu.AppendItem(item)
837 self.Bind(wx.EVT_MENU, handler, item)
844 """!Import maps menu (import, link)
850 """!Create new workspace file
852 Erase current workspace settings first
854 Debug.msg(4,
"GMFrame.OnWorkspaceNew():")
866 dlg = wx.MessageDialog(self, message = _(
"Current workspace is not empty. "
867 "Do you want to store current settings "
868 "to workspace file?"),
869 caption = _(
"Create new workspace?"),
870 style = wx.YES_NO | wx.YES_DEFAULT | \
871 wx.CANCEL | wx.ICON_QUESTION)
872 ret = dlg.ShowModal()
875 elif ret == wx.ID_CANCEL:
882 maptree.DeleteAllItems()
885 maptree.root = maptree.AddRoot(
"Map Layers")
886 self.
GetLayerTree().SetPyData(maptree.root, (
None,
None))
894 """!Open file with workspace definition"""
895 dlg = wx.FileDialog(parent = self, message = _(
"Choose workspace file"),
896 defaultDir = os.getcwd(), wildcard = _(
"GRASS Workspace File (*.gxw)|*.gxw"))
899 if dlg.ShowModal() == wx.ID_OK:
900 filename = dlg.GetPath()
905 Debug.msg(4,
"GMFrame.OnWorkspaceOpen(): filename=%s" % filename)
916 """!Load layer tree definition stored in GRASS Workspace XML file (gxw)
918 @todo Validate against DTD
920 @return True on success
921 @return False on error
924 dtdFilename = os.path.join(globalvar.ETCWXDIR,
"xml",
"grass-gxw.dtd")
928 gxwXml = ProcessWorkspaceFile(etree.parse(filename))
930 GError(parent = self,
931 message = _(
"Reading workspace file <%s> failed.\n"
932 "Invalid file, unable to parse XML document.") % filename)
935 busy = wx.BusyInfo(message = _(
"Please wait, loading workspace..."),
942 if not UserSettings.Get(group =
'general', key =
'workspace',
943 subkey = [
'posManager',
'enabled']):
944 if gxwXml.layerManager[
'pos']:
945 self.SetPosition(gxwXml.layerManager[
'pos'])
946 if gxwXml.layerManager[
'size']:
947 self.SetSize(gxwXml.layerManager[
'size'])
954 for display
in gxwXml.displays:
955 mapdisp = self.
NewDisplay(name = display[
'name'], show =
False)
956 mapdisplay.append(mapdisp)
957 maptree = self.notebookLayers.GetPage(displayId).maptree
960 mapdisp.SetProperties(render = display[
'render'],
961 mode = display[
'mode'],
962 showCompExtent = display[
'showCompExtent'],
963 alignExtent = display[
'alignExtent'],
964 constrainRes = display[
'constrainRes'],
965 projection = display[
'projection'][
'enabled'])
967 if display[
'projection'][
'enabled']:
968 if display[
'projection'][
'epsg']:
969 UserSettings.Set(group =
'display', key =
'projection', subkey =
'epsg',
970 value = display[
'projection'][
'epsg'])
971 if display[
'projection'][
'proj']:
972 UserSettings.Set(group =
'display', key =
'projection', subkey =
'proj4',
973 value = display[
'projection'][
'proj'])
976 if not UserSettings.Get(group =
'general', key =
'workspace', subkey = [
'posDisplay',
'enabled']):
978 mapdisp.SetPosition(display[
'pos'])
980 mapdisp.SetSize(display[
'size'])
983 if display[
'extent']:
984 w, s, e, n = display[
'extent']
985 region = maptree.Map.region = maptree.Map.GetRegion(w = w, s = s, e = e, n = n)
986 mapdisp.GetWindow().ResetZoomHistory()
987 mapdisp.GetWindow().ZoomHistory(region[
'n'],
999 for layer
in gxwXml.layers:
1000 display = layer[
'display']
1001 maptree = self.notebookLayers.GetPage(display).maptree
1003 newItem = maptree.AddLayer(ltype = layer[
'type'],
1004 lname = layer[
'name'],
1005 lchecked = layer[
'checked'],
1006 lopacity = layer[
'opacity'],
1007 lcmd = layer[
'cmd'],
1008 lgroup = layer[
'group'],
1009 lnviz = layer[
'nviz'],
1010 lvdigit = layer[
'vdigit'])
1012 if layer.has_key(
'selected'):
1013 if layer[
'selected']:
1014 selected.append((maptree, newItem))
1016 maptree.SelectItem(newItem, select =
False)
1018 for maptree, layer
in selected:
1019 if not maptree.IsSelected(layer):
1020 maptree.SelectItem(layer, select =
True)
1021 maptree.layer_selected = layer
1025 for idx, mdisp
in enumerate(mapdisplay):
1026 mdisp.MapWindow2D.UpdateMap()
1028 if gxwXml.displays[idx][
'viewMode'] ==
'3d':
1030 self.nviz.UpdateState(view = gxwXml.nviz_state[
'view'],
1031 iview = gxwXml.nviz_state[
'iview'],
1032 light = gxwXml.nviz_state[
'light'])
1033 mdisp.MapWindow3D.constants = gxwXml.nviz_state[
'constants']
1034 for idx, constant
in enumerate(mdisp.MapWindow3D.constants):
1035 mdisp.MapWindow3D.AddConstant(constant, idx + 1)
1036 for page
in (
'view',
'light',
'fringe',
'constant',
'cplane'):
1037 self.nviz.UpdatePage(page)
1038 self.nviz.UpdateSettings()
1039 mdisp.toolbars[
'map'].combo.SetSelection(1)
1046 """!Load map layers from GRC file (Tcl/Tk GUI) into map layer tree"""
1047 dlg = wx.FileDialog(parent = self, message = _(
"Choose GRC file to load"),
1048 defaultDir = os.getcwd(), wildcard = _(
"Old GRASS Workspace File (*.grc)|*.grc"))
1051 if dlg.ShowModal() == wx.ID_OK:
1052 filename = dlg.GetPath()
1057 Debug.msg(4,
"GMFrame.OnWorkspaceLoadGrcFile(): filename=%s" % filename)
1063 busy = wx.BusyInfo(message = _(
"Please wait, loading workspace..."),
1068 for layer
in ProcessGrcFile(filename).read(self):
1069 maptree = self.notebookLayers.GetPage(layer[
'display']).maptree
1070 newItem = maptree.AddLayer(ltype = layer[
'type'],
1071 lname = layer[
'name'],
1072 lchecked = layer[
'checked'],
1073 lopacity = layer[
'opacity'],
1074 lcmd = layer[
'cmd'],
1075 lgroup = layer[
'group'])
1081 maptree.Map.ReverseListOfLayers()
1084 """!Save workspace definition to selected file"""
1085 dlg = wx.FileDialog(parent = self, message = _(
"Choose file to save current workspace"),
1086 defaultDir = os.getcwd(), wildcard = _(
"GRASS Workspace File (*.gxw)|*.gxw"), style = wx.FD_SAVE)
1089 if dlg.ShowModal() == wx.ID_OK:
1090 filename = dlg.GetPath()
1096 if filename[-4:] !=
".gxw":
1099 if os.path.exists(filename):
1100 dlg = wx.MessageDialog(self, message = _(
"Workspace file <%s> already exists. "
1101 "Do you want to overwrite this file?") % filename,
1102 caption = _(
"Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
1103 if dlg.ShowModal() != wx.ID_YES:
1107 Debug.msg(4,
"GMFrame.OnWorkspaceSaveAs(): filename=%s" % filename)
1114 """!Save file with workspace definition"""
1116 dlg = wx.MessageDialog(self, message = _(
"Workspace file <%s> already exists. "
1117 "Do you want to overwrite this file?") % \
1119 caption = _(
"Save workspace"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
1120 if dlg.ShowModal() == wx.ID_NO:
1123 Debug.msg(4,
"GMFrame.OnWorkspaceSave(): filename=%s" % self.
workspaceFile)
1131 """!Save layer tree layout to workspace file
1133 Return True on success, False on error
1135 tmpfile = tempfile.TemporaryFile(mode =
'w+b')
1137 WriteWorkspaceFile(lmgr = self, file = tmpfile)
1138 except StandardError, e:
1139 GError(parent = self,
1140 message = _(
"Writing current settings to workspace file "
1145 mfile = open(filename,
"w")
1147 for line
in tmpfile.readlines():
1150 GError(parent = self,
1151 message = _(
"Unable to open file <%s> for writing.") % filename)
1159 """!Close file with workspace definition
1161 If workspace has been modified ask user to save the changes.
1163 Debug.msg(4,
"GMFrame.OnWorkspaceClose(): file=%s" % self.
workspaceFile)
1173 """!Close current map display window
1179 """!Close all open map display windows
1182 for page
in range(0, self.notebookLayers.GetPageCount()):
1183 displays.append(self.notebookLayers.GetPage(page).maptree.GetMapDisplay())
1185 for display
in displays:
1186 display.OnCloseWindow(event)
1189 """!Change Map Display name"""
1191 dlg = wx.TextEntryDialog(self, message = _(
"Enter new name:"),
1192 caption = _(
"Rename Map Display"), defaultValue = name)
1193 if dlg.ShowModal() == wx.ID_OK:
1194 name = dlg.GetValue()
1195 self.notebookLayers.SetPageText(page = self.
currentPageNum, text = name)
1197 mapdisplay.SetTitle(_(
"GRASS GIS %(version) Map Display: %(name)s - Location: %(loc)s") % \
1198 {
'version' : grass.version()[
'version'],
1200 'loc' : grass.gisenv()[
"LOCATION_NAME"] })
1204 """!Launches dialog for raster color rules
1206 ctable = RasterColorTable(self, layerTree = self.
GetLayerTree())
1208 ctable.CentreOnScreen()
1211 """!Launches dialog for vector color rules
1213 ctable = VectorColorTable(self, layerTree = self.
GetLayerTree(),
1214 attributeType =
'color')
1216 ctable.CentreOnScreen()
1220 Run commands that need xterm
1222 self.
OnXTerm(event, need_xmon =
False)
1226 Run commands that need interactive xmon
1228 @param need_xmon True to start X monitor
1231 if os.getenv(
'GRASS_RENDER_IMMEDIATE'):
1232 del os.environ[
'GRASS_RENDER_IMMEDIATE']
1243 for line
in ret.split(
'\n'):
1245 if line.startswith(
'x')
and 'not running' in line:
1246 xmonlist.append(line[0:2])
1252 cmdlist = [
'd.mon', xmon]
1253 p = Command(cmdlist, wait=
False)
1257 command =
' '.join(command)
1259 gisbase = os.environ[
'GISBASE']
1261 if sys.platform ==
"win32":
1262 runbat = os.path.join(gisbase,
'etc',
'grass-run.bat')
1263 cmdlist = [
"start", runbat, runbat, command]
1265 if sys.platform ==
"darwin":
1266 xtermwrapper = os.path.join(gisbase,
'etc',
'grass-xterm-mac')
1268 xtermwrapper = os.path.join(gisbase,
'etc',
'grass-xterm-wrapper')
1270 grassrun = os.path.join(gisbase,
'etc',
'grass-run.sh')
1271 cmdlist = [xtermwrapper,
'-e', grassrun, command]
1273 p = Command(cmdlist, wait=
False)
1276 os.environ[
'GRASS_RENDER_IMMEDIATE'] =
'TRUE'
1279 """!Show dialog for creating and editing groups.
1281 dlg = GroupDialog(self)
1282 dlg.CentreOnScreen()
1286 """!Install extension from GRASS Addons SVN repository"""
1287 win = InstallExtensionWindow(self, size = (650, 550))
1288 win.CentreOnScreen()
1292 """!Uninstall extension"""
1293 win = UninstallExtensionWindow(self, size = (650, 300))
1294 win.CentreOnScreen()
1298 """!General GUI preferences/settings
1300 if not self.
dialogs[
'preferences']:
1301 dlg = PreferencesDialog(parent = self)
1302 self.
dialogs[
'preferences'] = dlg
1303 self.
dialogs[
'preferences'].CenterOnScreen()
1307 self.
dialogs[
'preferences'].ShowModal()
1312 self.goutput.RunCmd([
'g.manual',
'-i'])
1315 """!Init histogram display canvas and tools
1318 win = HistogramFrame(self)
1320 win.CentreOnScreen()
1326 """!Launch profile tool
1330 win.CentreOnParent()
1336 """!Init map calculator for interactive creation of mapcalc statements
1344 win = MapCalcFrame(parent = self,
1346 win.CentreOnScreen()
1350 """!Init interactive vector cleaning
1352 from modules.vclean
import VectorCleaningFrame
1353 win = VectorCleaningFrame(parent = self)
1354 win.CentreOnScreen()
1358 """!Convert multiple DXF layers to GRASS vector map layers"""
1359 dlg = DxfImportDialog(parent = self)
1360 dlg.CentreOnScreen()
1364 """!Convert multiple GDAL layers to GRASS raster map layers"""
1365 dlg = GdalImportDialog(parent = self)
1366 dlg.CentreOnScreen()
1370 """!Link multiple GDAL layers to GRASS raster map layers"""
1371 dlg = GdalImportDialog(parent = self, link =
True)
1372 dlg.CentreOnScreen()
1376 """!Convert multiple OGR layers to GRASS vector map layers"""
1377 dlg = GdalImportDialog(parent = self, ogr =
True)
1378 dlg.CentreOnScreen()
1382 """!Links multiple OGR layers to GRASS vector map layers"""
1383 dlg = GdalImportDialog(parent = self, ogr =
True, link =
True)
1384 dlg.CentreOnScreen()
1388 """!Import data from OGC WMS server"""
1389 dlg = WMSDialog(parent = self, service =
'wms')
1390 dlg.CenterOnScreen()
1392 if dlg.ShowModal() == wx.ID_OK:
1393 layers = dlg.GetLayers()
1395 if len(layers.keys()) > 0:
1396 for layer
in layers.keys():
1398 'mapserver=%s' % dlg.GetSettings()[
'server'],
1399 'layers=%s' % layer,
1400 'output=%s' % layer,
1403 styles =
','.join(layers[layer])
1405 cmd.append(
'styles=%s' % styles)
1406 self.goutput.RunCmd(cmd, switchPage =
True)
1410 lcmd = [
'd.rast',
'map=%s' % layer],
1413 self.goutput.WriteWarning(_(
"Nothing to import. No WMS layer selected."))
1419 """!Show attribute table of the given vector map layer
1426 layer = tree.layer_selected
1434 maptype = tree.GetPyData(layer)[0][
'maplayer'].type
1438 if not maptype
or maptype !=
'vector':
1439 GMessage(parent = self,
1440 message = _(
"Selected map layer is not vector."))
1443 if not tree.GetPyData(layer)[0]:
1445 dcmd = tree.GetPyData(layer)[0][
'cmd']
1449 busy = wx.BusyInfo(message = _(
"Please wait, loading attribute data..."),
1453 dbmanager = AttributeManager(parent = self, id = wx.ID_ANY,
1454 size = wx.Size(500, 300),
1455 item = layer, log = self.
goutput,
1456 selection = selection)
1461 self.
dialogs[
'atm'].append(dbmanager)
1467 """!Create new layer tree and map display instance"""
1468 self.NewDisplayWMS()
1471 """!Create new layer tree and map display instance"""
1475 """!Create new layer tree, which will
1476 create an associated map display frame
1478 @param name name of new map display
1479 @param show show map display window if True
1481 @return reference to mapdisplay intance
1483 Debug.msg(1,
"GMFrame.NewDisplay(): idx=%d" % self.
displayIndex)
1491 self.notebookLayers.AddPage(self.
pg_panel, text = dispName, select =
True)
1492 self.
currentPage = self.notebookLayers.GetCurrentPage()
1495 self.currentPage.maptree = LayerTree(self.
currentPage, id = wx.ID_ANY, pos = wx.DefaultPosition,
1496 size = wx.DefaultSize, style = wx.TR_HAS_BUTTONS |
1497 wx.TR_LINES_AT_ROOT| wx.TR_HIDE_ROOT |
1498 wx.TR_DEFAULT_STYLE| wx.NO_BORDER | wx.FULL_REPAINT_ON_RESIZE,
1500 auimgr = self.
_auimgr, showMapDisplay = show)
1503 cb_boxsizer = wx.BoxSizer(wx.VERTICAL)
1504 cb_boxsizer.Add(self.
GetLayerTree(), proportion = 1, flag = wx.EXPAND, border = 1)
1505 self.currentPage.SetSizer(cb_boxsizer)
1507 self.currentPage.Layout()
1511 if UserSettings.Get(group =
'general', key =
'defWindowPos', subkey =
'enabled'):
1512 dim = UserSettings.Get(group =
'general', key =
'defWindowPos', subkey =
'dim')
1515 x, y = map(int, dim.split(
',')[idx:idx + 2])
1516 w, h = map(int, dim.split(
',')[idx + 2:idx + 4])
1527 """!Add selected map layers into layer tree"""
1528 dialog = MapLayersDialog(parent = self, title = _(
"Add selected map layers into layer tree"))
1530 if dialog.ShowModal() != wx.ID_OK:
1540 for layerName
in dialog.GetMapLayers():
1541 ltype = dialog.GetLayerType(cmd =
True)
1543 cmd = [
'd.rast',
'map=%s' % layerName]
1545 elif ltype ==
'rast3d':
1546 cmd = [
'd.rast3d',
'map=%s' % layerName]
1547 wxType =
'3d-raster'
1548 elif ltype ==
'vect':
1549 cmd = [
'd.vect',
'map=%s' % layerName]
1552 GError(parent = self,
1553 message = _(
"Unsupported map layer type <%s>.") % ltype)
1556 newItem = maptree.AddLayer(ltype = wxType,
1565 """!Add raster map layer"""
1570 self.notebook.SetSelectionByName(
'layers')
1574 """!Create misc raster popup-menu"""
1593 """!Add vector map to the current layer tree"""
1598 self.notebook.SetSelectionByName(
'layers')
1602 """!Create misc vector popup-menu"""
1614 """!Add thematic vector map to the current layer tree"""
1615 self.notebook.SetSelectionByName(
'layers')
1619 """!Add chart vector map to the current layer tree"""
1620 self.notebook.SetSelectionByName(
'layers')
1624 """!Create decoration overlay menu"""
1640 """!Add 3D raster map to the current layer tree"""
1641 self.notebook.SetSelectionByName(
'layers')
1645 """!Add RGB raster map to the current layer tree"""
1646 self.notebook.SetSelectionByName(
'layers')
1650 """!Add HIS raster map to the current layer tree"""
1651 self.notebook.SetSelectionByName(
'layers')
1655 """!Add shaded relief raster map to the current layer tree"""
1656 self.notebook.SetSelectionByName(
'layers')
1660 """!Add flow arrows raster map to the current layer tree"""
1661 self.notebook.SetSelectionByName(
'layers')
1663 resolution = tree.GetMapDisplay().GetProperty(
'resolution')
1666 if dlg.ShowModal() == wx.ID_YES:
1667 tree.GetMapDisplay().SetProperty(
'resolution',
True)
1673 """!Add cell number raster map to the current layer tree"""
1674 self.notebook.SetSelectionByName(
'layers')
1676 resolution = tree.GetMapDisplay().GetProperty(
'resolution')
1678 limitText = _(
"Note that cell values can only be displayed for "
1679 "regions of less than 10,000 cells.")
1681 if dlg.ShowModal() == wx.ID_YES:
1682 tree.GetMapDisplay().SetProperty(
'resolution',
True)
1691 """!Add command line map layer to the current layer tree"""
1696 self.notebook.SetSelectionByName(
'layers')
1703 """!Add layer group"""
1708 self.notebook.SetSelectionByName(
'layers')
1715 """!Add grid map layer to the current layer tree"""
1716 self.notebook.SetSelectionByName(
'layers')
1720 """!Add geodesic line map layer to the current layer tree"""
1721 self.notebook.SetSelectionByName(
'layers')
1725 """!Add rhumb map layer to the current layer tree"""
1726 self.notebook.SetSelectionByName(
'layers')
1730 """!Add vector labels map layer to the current layer tree"""
1735 self.notebook.SetSelectionByName(
'layers')
1742 """!Remove selected map layer from the current layer Tree
1748 if UserSettings.Get(group =
'manager', key =
'askOnRemoveLayer', subkey =
'enabled'):
1752 idx = name.find(
'(opacity')
1754 layerName +=
'<' + name[:idx].strip(
' ') +
'>,\n'
1756 layerName +=
'<' + name +
'>,\n'
1757 layerName = layerName.rstrip(
',\n')
1759 if len(layerName) > 2:
1760 message = _(
"Do you want to remove map layer(s)\n%s\n"
1761 "from layer tree?") % layerName
1763 message = _(
"Do you want to remove selected map layer(s) "
1766 dlg = wx.MessageDialog (parent = self, message = message,
1767 caption = _(
"Remove map layer"),
1768 style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
1770 if dlg.ShowModal() != wx.ID_YES:
1777 if self.
GetLayerTree().GetPyData(layer)[0][
'type'] ==
'group':
1783 kc = event.GetKeyCode()
1785 if event.ControlDown():
1786 if kc == wx.WXK_TAB:
1788 if self.notebook.GetSelection() == self.notebook.GetPageIndexByName(
'layers'):
1789 self.notebook.SetSelectionByName(
'output')
1791 self.notebook.SetSelectionByName(
'layers')
1799 if event.CtrlDown():
1808 """!Cleanup when wxGUI is quitted"""
1810 if self.goutput.btnCmdProtocol.GetValue():
1811 self.goutput.CmdProtocolSave()
1814 self._auimgr.UnInit()
1821 UserSettings.Get(group =
'manager', key =
'askOnQuit', subkey =
'enabled'):
1823 message = _(
"Do you want to save changes in the workspace?")
1825 message = _(
"Do you want to store current settings "
1826 "to workspace file?")
1829 if maptree.GetCount() > 0:
1830 dlg = wx.MessageDialog(self,
1832 caption = _(
"Quit GRASS GUI"),
1833 style = wx.YES_NO | wx.YES_DEFAULT |
1834 wx.CANCEL | wx.ICON_QUESTION | wx.CENTRE)
1835 ret = dlg.ShowModal()
1836 if ret == wx.ID_YES:
1841 elif ret == wx.ID_CANCEL:
1843 if hasattr(event,
'Veto'):
1850 UserSettings.Set(group =
'manager', key =
'askOnQuit', subkey =
'enabled',
1855 self.notebookLayers.DeleteAllPages()
1857 self._auimgr.UnInit()
1861 """!Show dialog message 'No layer selected'"""
1862 wx.MessageBox(parent = self,
1863 message = _(
"No map layer selected. Operation canceled."),
1864 caption = _(
"Message"),
1865 style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
1868 """!Returns dialog for d.rast.num, d.rast.arrow
1869 when display resolution is not constrained
1871 @param limitText adds a note about cell limit
1873 message = _(
"Display resolution is currently not constrained to "
1874 "computational settings. "
1875 "It's suggested to constrain map to region geometry. "
1876 "Do you want to constrain "
1879 message +=
"\n\n%s" % _(limitText)
1880 dlg = wx.MessageDialog(parent = self,
1882 caption = _(
"Constrain map to region geometry?"),
1883 style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION | wx.CENTRE)
def MsgNoLayerSelected
Show dialog message 'No layer selected'.
def OnVectorCleaning
Init interactive vector cleaning.
def IsPaneShown
Check if pane (toolbar, ...) of given name is currently shown.
def OnRunScript
Run script.
def OnNewDisplayWMS
Create new layer tree and map display instance.
def OnProfile
Launch profile tool.
def OnXTermNoXMon
Run commands that need xterm.
def OnCreateMapset
Create new mapset.
def OnAddRasterShaded
Add shaded relief raster map to the current layer tree.
def _createNoteBook
Creates notebook widgets.
def OnAddRaster
Add raster map layer.
def OnDisplayClose
Close current map display window.
def OnVDigit
Start vector digitizer.
def _createTabMenu
Creates context menu for display tabs.
def _createMenuBar
Creates menu bar.
Location wizard - dialogs.
wxGUI Graphical Modeler (base classes & read/write)
Location wizard - creates a new GRASS Location.
def OnImportMenu
Import maps menu (import, link)
def OnSettingsChanged
Here can be functions which have to be called after EVT_SETTINGS_CHANGED.
def OnNewDisplay
Create new layer tree and map display instance.
def OnHistogram
Init histogram display canvas and tools.
Layer Manager frame with notebook widget for controlling GRASS GIS.
wxGUI Interactive Python Shell for Layer Manager
def OnDeleteLayer
Remove selected map layer from the current layer Tree.
def OnImportWMS
Import data from OGC WMS server.
def AddNvizTools
Add nviz notebook page.
def OnUninstallExtension
Uninstall extension.
def OnPsMap
Launch Cartographic Composer.
def RemoveNvizTools
Remove nviz notebook page.
def OnImportGdalLayers
Convert multiple GDAL layers to GRASS raster map layers.
Open/save workspace definition file.
def OnCBPageChanged
Page in notebook (display) changed.
GRASS Attribute Table Manager.
def OnAddRasterHIS
Add HIS raster map to the current layer tree.
def OnVectorRules
Launches dialog for vector color rules.
def OnLinkOgrLayers
Links multiple OGR layers to GRASS vector map layers.
def GetMapDisplay
Get current map display.
def OnGModeler
Launch Graphical Modeler.
Various dialogs used in wxGUI.
def _popupMenu
Create popup menu.
def OnAddRaster3D
Add 3D raster map to the current layer tree.
def OnAddVectorChart
Add chart vector map to the current layer tree.
wxGUI Graphical Modeler for creating, editing, and managing models
def OnEditImageryGroups
Show dialog for creating and editing groups.
def OnPreferences
General GUI preferences/settings.
def SetAddOnPath
Set default AddOn path.
def OnAddVectorMisc
Create misc vector popup-menu.
Georectification module for GRASS GIS.
Plotting histogram based on d.histogram.
def OnDisplayCloseAll
Close all open map display windows.
def OnAddMaps
Add selected map layers into layer tree.
def OnMenuCmd
Parse command selected from menu.
def OnAddLabels
Add vector labels map layer to the current layer tree.
def OnAddVector
Add vector map to the current layer tree.
def SaveToWorkspaceFile
Save layer tree layout to workspace file.
def OnAddVectorTheme
Add thematic vector map to the current layer tree.
def OnKeyDown
Key pressed.
def GetMenuCmd
Get GRASS command from menu item.
def OnWorkspaceSaveAs
Save workspace definition to selected file.
def OnWorkspaceNew
Create new workspace file.
def OnRasterRules
Launches dialog for raster color rules.
def OnCloseWindow
Cleanup when wxGUI is quitted.
def _setCopyingOfSelectedText
def OnAboutGRASS
Display 'About GRASS' dialog.
def CreateNewVector
Create new vector map layer.
def OnGCPManager
Launch georectifier module.
def OnInstallExtension
Install extension from GRASS Addons SVN repository.
def OnAddOverlay
Create decoration overlay menu.
def MsgDisplayResolution
Returns dialog for d.rast.num, d.rast.arrow when display resolution is not constrained.
Utility classes for map layer management.
def OnAddRasterArrow
Add flow arrows raster map to the current layer tree.
def OnAddRasterNum
Add cell number raster map to the current layer tree.
Mainframe for displaying profile of one or more raster maps.
def OnSystemInfo
Print system information.
Misc utilities for wxGUI.
def OnMapsets
Launch mapset access dialog.
def OnAddGroup
Add layer group.
def OnLinkGdalLayers
Link multiple GDAL layers to GRASS raster map layers.
def LoadWorkspaceFile
Load layer tree definition stored in GRASS Workspace XML file (gxw)
def OnMapCalculator
Init map calculator for interactive creation of mapcalc statements.
def OnAddRhumb
Add rhumb map layer to the current layer tree.
def OnAddGrid
Add grid map layer to the current layer tree.
def OnAddRasterMisc
Create misc raster popup-menu.
def OnXTerm
Run commands that need interactive xmon.
def OnWorkspaceClose
Close file with workspace definition.
def OnCBPageClosed
Page of notebook closed Also close associated map display.
GRASS Addons extensions management classes.
def OnImportDxfFile
Convert multiple DXF layers to GRASS vector map layers.
def NewDisplay
Create new layer tree, which will create an associated map display frame.
def GetLogWindow
Get widget for command output.
def OnLocationWizard
Launch location wizard.
def GetLayerNotebook
Get Layers Notebook.
def OnAddCommand
Add command line map layer to the current layer tree.
def OnShowAttributeTable
Show attribute table of the given vector map layer.
def OnNewVector
Create new vector map layer.
def RunMenuCmd
Run command selected from menu.
def WorkspaceChanged
Update window title.
def OnWorkspaceOpen
Open file with workspace definition.
def OnWorkspaceSave
Save file with workspace definition.
def OnRenameDisplay
Change Map Display name.
def GetLayerTree
Get current layer tree.
def OnWorkspaceLoadGrcFile
Load map layers from GRC file (Tcl/Tk GUI) into map layer tree.
def RunCommand
Run GRASS command.
def OnImportOgrLayers
Convert multiple OGR layers to GRASS vector map layers.
def OnAddRasterRGB
Add RGB raster map to the current layer tree.
def OnPageChanged
Page in notebook changed.
def OnAddGeodesic
Add geodesic line map layer to the current layer tree.