[GRASS-SVN] r68374 - in grass/trunk/gui: scripts wxpython wxpython/animation wxpython/core wxpython/datacatalog wxpython/dbmgr wxpython/docs/wxgui_sphinx wxpython/gcp wxpython/gmodeler wxpython/gui_core wxpython/iclass wxpython/icons wxpython/iscatt wxpython/lmgr wxpython/location_wizard wxpython/mapdisp wxpython/mapswipe wxpython/mapwin wxpython/modules wxpython/nviz wxpython/psmap wxpython/rdigit wxpython/rlisetup wxpython/timeline wxpython/tools wxpython/tplot wxpython/vdigit wxpython/vnet wxpython/web_services wxpython/wxplot
svn_grass at osgeo.org
svn_grass at osgeo.org
Tue May 3 12:04:42 PDT 2016
Author: martinl
Date: 2016-05-03 12:04:42 -0700 (Tue, 03 May 2016)
New Revision: 68374
Modified:
grass/trunk/gui/scripts/d.wms.py
grass/trunk/gui/wxpython/animation/anim.py
grass/trunk/gui/wxpython/animation/controller.py
grass/trunk/gui/wxpython/animation/data.py
grass/trunk/gui/wxpython/animation/dialogs.py
grass/trunk/gui/wxpython/animation/frame.py
grass/trunk/gui/wxpython/animation/g.gui.animation.py
grass/trunk/gui/wxpython/animation/mapwindow.py
grass/trunk/gui/wxpython/animation/nviztask.py
grass/trunk/gui/wxpython/animation/provider.py
grass/trunk/gui/wxpython/animation/temporal_manager.py
grass/trunk/gui/wxpython/animation/toolbars.py
grass/trunk/gui/wxpython/animation/utils.py
grass/trunk/gui/wxpython/core/__init__.py
grass/trunk/gui/wxpython/core/debug.py
grass/trunk/gui/wxpython/core/gcmd.py
grass/trunk/gui/wxpython/core/gconsole.py
grass/trunk/gui/wxpython/core/giface.py
grass/trunk/gui/wxpython/core/globalvar.py
grass/trunk/gui/wxpython/core/gthread.py
grass/trunk/gui/wxpython/core/layerlist.py
grass/trunk/gui/wxpython/core/menutree.py
grass/trunk/gui/wxpython/core/render.py
grass/trunk/gui/wxpython/core/settings.py
grass/trunk/gui/wxpython/core/toolboxes.py
grass/trunk/gui/wxpython/core/treemodel.py
grass/trunk/gui/wxpython/core/units.py
grass/trunk/gui/wxpython/core/utils.py
grass/trunk/gui/wxpython/core/workspace.py
grass/trunk/gui/wxpython/core/ws.py
grass/trunk/gui/wxpython/datacatalog/catalog.py
grass/trunk/gui/wxpython/datacatalog/frame.py
grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py
grass/trunk/gui/wxpython/datacatalog/toolbars.py
grass/trunk/gui/wxpython/datacatalog/tree.py
grass/trunk/gui/wxpython/dbmgr/__init__.py
grass/trunk/gui/wxpython/dbmgr/base.py
grass/trunk/gui/wxpython/dbmgr/dialogs.py
grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py
grass/trunk/gui/wxpython/dbmgr/manager.py
grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py
grass/trunk/gui/wxpython/dbmgr/vinfo.py
grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py
grass/trunk/gui/wxpython/gcp/__init__.py
grass/trunk/gui/wxpython/gcp/g.gui.gcp.py
grass/trunk/gui/wxpython/gcp/manager.py
grass/trunk/gui/wxpython/gcp/mapdisplay.py
grass/trunk/gui/wxpython/gcp/statusbar.py
grass/trunk/gui/wxpython/gcp/toolbars.py
grass/trunk/gui/wxpython/gis_set.py
grass/trunk/gui/wxpython/gis_set_error.py
grass/trunk/gui/wxpython/gmodeler/__init__.py
grass/trunk/gui/wxpython/gmodeler/dialogs.py
grass/trunk/gui/wxpython/gmodeler/frame.py
grass/trunk/gui/wxpython/gmodeler/g.gui.gmodeler.py
grass/trunk/gui/wxpython/gmodeler/giface.py
grass/trunk/gui/wxpython/gmodeler/menudata.py
grass/trunk/gui/wxpython/gmodeler/model.py
grass/trunk/gui/wxpython/gmodeler/preferences.py
grass/trunk/gui/wxpython/gmodeler/toolbars.py
grass/trunk/gui/wxpython/gui_core/__init__.py
grass/trunk/gui/wxpython/gui_core/dialogs.py
grass/trunk/gui/wxpython/gui_core/forms.py
grass/trunk/gui/wxpython/gui_core/ghelp.py
grass/trunk/gui/wxpython/gui_core/goutput.py
grass/trunk/gui/wxpython/gui_core/gselect.py
grass/trunk/gui/wxpython/gui_core/mapdisp.py
grass/trunk/gui/wxpython/gui_core/menu.py
grass/trunk/gui/wxpython/gui_core/preferences.py
grass/trunk/gui/wxpython/gui_core/prompt.py
grass/trunk/gui/wxpython/gui_core/pyedit.py
grass/trunk/gui/wxpython/gui_core/pystc.py
grass/trunk/gui/wxpython/gui_core/query.py
grass/trunk/gui/wxpython/gui_core/simplelmgr.py
grass/trunk/gui/wxpython/gui_core/toolbars.py
grass/trunk/gui/wxpython/gui_core/treeview.py
grass/trunk/gui/wxpython/gui_core/vselect.py
grass/trunk/gui/wxpython/gui_core/widgets.py
grass/trunk/gui/wxpython/iclass/__init__.py
grass/trunk/gui/wxpython/iclass/dialogs.py
grass/trunk/gui/wxpython/iclass/digit.py
grass/trunk/gui/wxpython/iclass/frame.py
grass/trunk/gui/wxpython/iclass/g.gui.iclass.py
grass/trunk/gui/wxpython/iclass/plots.py
grass/trunk/gui/wxpython/iclass/statistics.py
grass/trunk/gui/wxpython/iclass/toolbars.py
grass/trunk/gui/wxpython/icons/__init__.py
grass/trunk/gui/wxpython/icons/icon.py
grass/trunk/gui/wxpython/iscatt/__init__.py
grass/trunk/gui/wxpython/iscatt/controllers.py
grass/trunk/gui/wxpython/iscatt/core_c.py
grass/trunk/gui/wxpython/iscatt/dialogs.py
grass/trunk/gui/wxpython/iscatt/frame.py
grass/trunk/gui/wxpython/iscatt/iscatt_core.py
grass/trunk/gui/wxpython/iscatt/plots.py
grass/trunk/gui/wxpython/iscatt/toolbars.py
grass/trunk/gui/wxpython/lmgr/__init__.py
grass/trunk/gui/wxpython/lmgr/frame.py
grass/trunk/gui/wxpython/lmgr/giface.py
grass/trunk/gui/wxpython/lmgr/layertree.py
grass/trunk/gui/wxpython/lmgr/menudata.py
grass/trunk/gui/wxpython/lmgr/pyshell.py
grass/trunk/gui/wxpython/lmgr/toolbars.py
grass/trunk/gui/wxpython/location_wizard/__init__.py
grass/trunk/gui/wxpython/location_wizard/base.py
grass/trunk/gui/wxpython/location_wizard/dialogs.py
grass/trunk/gui/wxpython/location_wizard/wizard.py
grass/trunk/gui/wxpython/mapdisp/__init__.py
grass/trunk/gui/wxpython/mapdisp/frame.py
grass/trunk/gui/wxpython/mapdisp/gprint.py
grass/trunk/gui/wxpython/mapdisp/main.py
grass/trunk/gui/wxpython/mapdisp/statusbar.py
grass/trunk/gui/wxpython/mapdisp/test_mapdisp.py
grass/trunk/gui/wxpython/mapdisp/toolbars.py
grass/trunk/gui/wxpython/mapswipe/__init__.py
grass/trunk/gui/wxpython/mapswipe/dialogs.py
grass/trunk/gui/wxpython/mapswipe/frame.py
grass/trunk/gui/wxpython/mapswipe/g.gui.mapswipe.py
grass/trunk/gui/wxpython/mapswipe/mapwindow.py
grass/trunk/gui/wxpython/mapswipe/toolbars.py
grass/trunk/gui/wxpython/mapwin/__init__.py
grass/trunk/gui/wxpython/mapwin/analysis.py
grass/trunk/gui/wxpython/mapwin/base.py
grass/trunk/gui/wxpython/mapwin/buffered.py
grass/trunk/gui/wxpython/mapwin/decorations.py
grass/trunk/gui/wxpython/mapwin/graphics.py
grass/trunk/gui/wxpython/modules/__init__.py
grass/trunk/gui/wxpython/modules/colorrules.py
grass/trunk/gui/wxpython/modules/extensions.py
grass/trunk/gui/wxpython/modules/histogram.py
grass/trunk/gui/wxpython/modules/import_export.py
grass/trunk/gui/wxpython/modules/mapsets_picker.py
grass/trunk/gui/wxpython/modules/mcalc_builder.py
grass/trunk/gui/wxpython/modules/vclean.py
grass/trunk/gui/wxpython/modules/vkrige.py
grass/trunk/gui/wxpython/nviz/__init__.py
grass/trunk/gui/wxpython/nviz/animation.py
grass/trunk/gui/wxpython/nviz/main.py
grass/trunk/gui/wxpython/nviz/mapwindow.py
grass/trunk/gui/wxpython/nviz/preferences.py
grass/trunk/gui/wxpython/nviz/tools.py
grass/trunk/gui/wxpython/nviz/workspace.py
grass/trunk/gui/wxpython/nviz/wxnviz.py
grass/trunk/gui/wxpython/psmap/__init__.py
grass/trunk/gui/wxpython/psmap/dialogs.py
grass/trunk/gui/wxpython/psmap/frame.py
grass/trunk/gui/wxpython/psmap/g.gui.psmap.py
grass/trunk/gui/wxpython/psmap/instructions.py
grass/trunk/gui/wxpython/psmap/menudata.py
grass/trunk/gui/wxpython/psmap/toolbars.py
grass/trunk/gui/wxpython/psmap/utils.py
grass/trunk/gui/wxpython/rdigit/__init__.py
grass/trunk/gui/wxpython/rdigit/controller.py
grass/trunk/gui/wxpython/rdigit/dialogs.py
grass/trunk/gui/wxpython/rdigit/toolbars.py
grass/trunk/gui/wxpython/rlisetup/__init__.py
grass/trunk/gui/wxpython/rlisetup/frame.py
grass/trunk/gui/wxpython/rlisetup/functions.py
grass/trunk/gui/wxpython/rlisetup/g.gui.rlisetup.py
grass/trunk/gui/wxpython/rlisetup/sampling_frame.py
grass/trunk/gui/wxpython/rlisetup/wizard.py
grass/trunk/gui/wxpython/timeline/__init__.py
grass/trunk/gui/wxpython/timeline/frame.py
grass/trunk/gui/wxpython/timeline/g.gui.timeline.py
grass/trunk/gui/wxpython/tools/build_modules_xml.py
grass/trunk/gui/wxpython/tools/update_menudata.py
grass/trunk/gui/wxpython/tplot/__init__.py
grass/trunk/gui/wxpython/tplot/frame.py
grass/trunk/gui/wxpython/tplot/g.gui.tplot.py
grass/trunk/gui/wxpython/vdigit/__init__.py
grass/trunk/gui/wxpython/vdigit/dialogs.py
grass/trunk/gui/wxpython/vdigit/g.gui.vdigit.py
grass/trunk/gui/wxpython/vdigit/main.py
grass/trunk/gui/wxpython/vdigit/mapwindow.py
grass/trunk/gui/wxpython/vdigit/preferences.py
grass/trunk/gui/wxpython/vdigit/toolbars.py
grass/trunk/gui/wxpython/vdigit/wxdigit.py
grass/trunk/gui/wxpython/vdigit/wxdisplay.py
grass/trunk/gui/wxpython/vnet/__init__.py
grass/trunk/gui/wxpython/vnet/dialogs.py
grass/trunk/gui/wxpython/vnet/toolbars.py
grass/trunk/gui/wxpython/vnet/vnet_core.py
grass/trunk/gui/wxpython/vnet/vnet_data.py
grass/trunk/gui/wxpython/vnet/vnet_utils.py
grass/trunk/gui/wxpython/vnet/widgets.py
grass/trunk/gui/wxpython/web_services/__init__.py
grass/trunk/gui/wxpython/web_services/cap_interface.py
grass/trunk/gui/wxpython/web_services/dialogs.py
grass/trunk/gui/wxpython/web_services/widgets.py
grass/trunk/gui/wxpython/wxgui.py
grass/trunk/gui/wxpython/wxplot/__init__.py
grass/trunk/gui/wxpython/wxplot/base.py
grass/trunk/gui/wxpython/wxplot/dialogs.py
grass/trunk/gui/wxpython/wxplot/histogram.py
grass/trunk/gui/wxpython/wxplot/profile.py
grass/trunk/gui/wxpython/wxplot/scatter.py
Log:
wxGUI: apply pep8
(autopep8 --in-place --aggressive --recursive --experimental --jobs 4)
Modified: grass/trunk/gui/scripts/d.wms.py
===================================================================
--- grass/trunk/gui/scripts/d.wms.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/scripts/d.wms.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,7 +20,7 @@
#% keyword: raster
#% keyword: import
#% keyword: WMS
-#% keyword: WMTS
+#% keyword: WMTS
#% keyword: OnEarth
#%end
@@ -66,8 +66,8 @@
#%option
#% key: srs
#% type: integer
-#% description: EPSG code of requested source projection
-#% answer:4326
+#% description: EPSG code of requested source projection
+#% answer:4326
#% guisection: Request
#%end
@@ -161,19 +161,20 @@
from grass.script import core as grass
sys.path.append(os.path.join(os.getenv("GISBASE"), "etc", "r.in.wms"))
-
+
+
def GetRegion():
"""!Parse region from GRASS_REGION env var.
"""
region = os.environ["GRASS_REGION"]
- conv_reg_vals = {'east' : 'e',
- 'north' : 'n',
- 'west' : 'w',
- 'south' : 's',
- 'rows' : 'rows',
- 'cols' : 'cols',
- 'e-w resol' : 'ewres',
- 'n-s resol' : 'nsres'}
+ conv_reg_vals = {'east': 'e',
+ 'north': 'n',
+ 'west': 'w',
+ 'south': 's',
+ 'rows': 'rows',
+ 'cols': 'cols',
+ 'e-w resol': 'ewres',
+ 'n-s resol': 'nsres'}
keys_to_convert = conv_reg_vals.keys()
@@ -183,12 +184,13 @@
for r in region:
r = r.split(':')
r[0] = r[0].strip()
-
+
if r[0] in keys_to_convert:
conv_region[conv_reg_vals[r[0]]] = float(r[1])
return conv_region
+
def main():
options['region'] = GetRegion()
@@ -200,8 +202,8 @@
grass.debug("Using GDAL WMS driver")
from wms_gdal_drv import WMSGdalDrv
wms = WMSGdalDrv()
-
- temp_map = wms.GetMap(options, flags)
+
+ temp_map = wms.GetMap(options, flags)
os.rename(temp_map, os.environ["GRASS_RENDER_FILE"])
return 0
Modified: grass/trunk/gui/wxpython/animation/anim.py
===================================================================
--- grass/trunk/gui/wxpython/animation/anim.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/anim.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -21,6 +21,7 @@
class Animation(wx.EvtHandler):
"""Animation class specifies which frame to show at which instance."""
+
def __init__(self):
wx.EvtHandler.__init__(self)
@@ -103,7 +104,9 @@
if not self.IsActive():
return
self.currentIndex = 0
- self.callbackEndAnimation(self.currentIndex, self.GetFrame(self.currentIndex))
+ self.callbackEndAnimation(
+ self.currentIndex, self.GetFrame(
+ self.currentIndex))
def _arrivedToEnd(self):
"""Decides which action to do after animation end (stop, repeat)."""
@@ -132,7 +135,9 @@
if not self.IsActive():
return
- self.callbackUpdateFrame(self.currentIndex, self.GetFrame(self.currentIndex))
+ self.callbackUpdateFrame(
+ self.currentIndex, self.GetFrame(
+ self.currentIndex))
if self.orientation == Orientation.FORWARD:
self.currentIndex += 1
if self.currentIndex == self.count:
@@ -147,7 +152,9 @@
if not self.IsActive():
return
self.currentIndex = index
- self.callbackUpdateFrame(self.currentIndex, self.GetFrame(self.currentIndex))
+ self.callbackUpdateFrame(
+ self.currentIndex, self.GetFrame(
+ self.currentIndex))
def PreviousFrameIndex(self):
if not self.IsActive():
@@ -173,7 +180,7 @@
if self.currentIndex == -1:
self.currentIndex = 0
-#def test():
+# def test():
# import wx
# app = wx.PySimpleApp()
# a = Animation()
@@ -187,5 +194,5 @@
# app.MainLoop()
#
#
-#if __name__ == '__main__':
+# if __name__ == '__main__':
# test()
Modified: grass/trunk/gui/wxpython/animation/controller.py
===================================================================
--- grass/trunk/gui/wxpython/animation/controller.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/controller.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,7 +29,9 @@
class AnimationController(wx.EvtHandler):
- def __init__(self, frame, sliders, animations, mapwindows, provider, bitmapPool, mapFilesPool):
+
+ def __init__(self, frame, sliders, animations, mapwindows,
+ provider, bitmapPool, mapFilesPool):
wx.EvtHandler.__init__(self)
self.mapwindows = mapwindows
@@ -50,10 +52,13 @@
self.bitmapProvider = provider
for anim, win in zip(self.animations, self.mapwindows):
anim.SetCallbackUpdateFrame(
- lambda index, dataId, win=win: self.UpdateFrame(index, win, dataId))
+ lambda index, dataId, win=win: self.UpdateFrame(
+ index, win, dataId))
anim.SetCallbackEndAnimation(
- lambda index, dataId, win=win: self.UpdateFrameEnd(index, win, dataId))
- anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
+ lambda index, dataId, win=win: self.UpdateFrameEnd(
+ index, win, dataId))
+ anim.SetCallbackOrientationChanged(
+ self.OrientationChangedInReverseMode)
for slider in self.sliders.values():
slider.SetCallbackSliderChanging(self.SliderChanging)
@@ -199,8 +204,12 @@
# if self.timer.IsRunning():
# running = True
self.EndAnimation()
- dlg = EditDialog(parent=self.frame, evalFunction=self.EvaluateInput,
- animationData=self.animationData, maxAnimations=len(self.animations))
+ dlg = EditDialog(
+ parent=self.frame,
+ evalFunction=self.EvaluateInput,
+ animationData=self.animationData,
+ maxAnimations=len(
+ self.animations))
dlg.CenterOnParent()
if dlg.ShowModal() == wx.ID_CANCEL:
dlg.Destroy()
@@ -220,8 +229,10 @@
break
if not found:
- GMessage(parent=self.frame,
- message=_("Maximum number of animations is %s.") % len(self.animations))
+ GMessage(
+ parent=self.frame,
+ message=_("Maximum number of animations is %s.") %
+ len(self.animations))
return
# running = False
@@ -232,9 +243,13 @@
animData = AnimationData()
# number of active animations
- animationIndex = len([anim for anim in self.animations if anim.IsActive()])
+ animationIndex = len(
+ [anim for anim in self.animations if anim.IsActive()])
animData.SetDefaultValues(windowIndex, animationIndex)
- dlg = InputDialog(parent=self.frame, mode='add', animationData=animData)
+ dlg = InputDialog(
+ parent=self.frame,
+ mode='add',
+ animationData=animData)
dlg.CenterOnParent()
if dlg.ShowModal() == wx.ID_CANCEL:
dlg.Destroy()
@@ -242,11 +257,14 @@
dlg.Destroy()
# check compatibility
if animData.windowIndex in indices:
- GMessage(parent=self.frame, message=_("More animations are using one window."
- " Please select different window for each animation."))
+ GMessage(
+ parent=self.frame, message=_(
+ "More animations are using one window."
+ " Please select different window for each animation."))
return
try:
- temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData])
+ temporalMode, tempManager = self.EvaluateInput(
+ self.animationData + [animData])
except GException as e:
GError(parent=self.frame, message=e.value, showTraceback=False)
return
@@ -299,9 +317,13 @@
if anim.viewMode == '2d':
anim.cmdMatrix = layerListToCmdsMatrix(anim.layerList)
else:
- anim.cmdMatrix = [(cmd,) for cmd in anim.GetNvizCommands()['commands']]
+ anim.cmdMatrix = [(cmd,)
+ for cmd in anim.GetNvizCommands()
+ ['commands']]
self._updateSlider(timeLabels=timeLabels)
- self._updateAnimations(activeIndices=indices, mapNamesDict=mapNamesDict)
+ self._updateAnimations(
+ activeIndices=indices,
+ mapNamesDict=mapNamesDict)
wx.Yield()
self._updateBitmapData()
# if running:
@@ -331,30 +353,34 @@
if i not in activeIndices:
self.animations[i].SetActive(False)
continue
- anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
+ anim = [anim for anim in self.animationData
+ if anim.windowIndex == i][0]
w, h = self.mapwindows[i].GetClientSize()
regions = anim.GetRegions(w, h)
- self.animations[i].SetFrames([HashCmds(cmdList, region)
- for cmdList, region in zip(anim.cmdMatrix, regions)])
+ self.animations[i].SetFrames(
+ [HashCmds(cmdList, region) for cmdList,
+ region in zip(anim.cmdMatrix, regions)])
self.animations[i].SetActive(True)
else:
for i in range(len(self.animations)):
if i not in activeIndices:
self.animations[i].SetActive(False)
continue
- anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
+ anim = [anim for anim in self.animationData
+ if anim.windowIndex == i][0]
w, h = self.mapwindows[i].GetClientSize()
regions = anim.GetRegions(w, h)
- identifiers = sampleCmdMatrixAndCreateNames(anim.cmdMatrix,
- mapNamesDict[anim.firstStdsNameType[0]],
- regions)
+ identifiers = sampleCmdMatrixAndCreateNames(
+ anim.cmdMatrix, mapNamesDict[
+ anim.firstStdsNameType[0]], regions)
self.animations[i].SetFrames(identifiers)
self.animations[i].SetActive(True)
def _updateWindows(self, activeIndices):
# add or remove window
for windowIndex in range(len(self.animations)):
- if not self.frame.IsWindowShown(windowIndex) and windowIndex in activeIndices:
+ if not self.frame.IsWindowShown(
+ windowIndex) and windowIndex in activeIndices:
self.frame.AddWindow(windowIndex)
elif self.frame.IsWindowShown(windowIndex) and windowIndex not in activeIndices:
self.frame.RemoveWindow(windowIndex)
@@ -370,18 +396,27 @@
else:
self._load3DData(animData)
self._loadLegend(animData)
- color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
- cpus = UserSettings.Get(group='animation', key='nprocs', subkey='value')
+ color = UserSettings.Get(
+ group='animation',
+ key='bgcolor',
+ subkey='color')
+ cpus = UserSettings.Get(
+ group='animation',
+ key='nprocs',
+ subkey='value')
self.bitmapProvider.Load(nprocs=cpus, bgcolor=color)
# clear pools
self.bitmapPool.Clear()
self.mapFilesPool.Clear()
def _set2DData(self, animationData):
- opacities = [layer.opacity for layer in animationData.layerList if layer.active]
+ opacities = [
+ layer.opacity for layer in animationData.layerList
+ if layer.active]
w, h = self.mapwindows[animationData.GetWindowIndex()].GetClientSize()
regions = animationData.GetRegions(w, h)
- self.bitmapProvider.SetCmds(animationData.cmdMatrix, opacities, regions)
+ self.bitmapProvider.SetCmds(
+ animationData.cmdMatrix, opacities, regions)
def _load3DData(self, animationData):
nviz = animationData.GetNvizCommands()
@@ -390,7 +425,8 @@
def _loadLegend(self, animationData):
if animationData.legendCmd:
try:
- bitmap = self.bitmapProvider.LoadOverlay(animationData.legendCmd)
+ bitmap = self.bitmapProvider.LoadOverlay(
+ animationData.legendCmd)
try:
from PIL import Image
for param in animationData.legendCmd:
@@ -400,7 +436,9 @@
break
except ImportError:
x, y = 0, 0
- self.mapwindows[animationData.windowIndex].SetOverlay(bitmap, x, y)
+ self.mapwindows[
+ animationData.windowIndex].SetOverlay(
+ bitmap, x, y)
except GException:
GError(message=_("Failed to display legend."))
else:
@@ -433,7 +471,8 @@
if temporalMode == TemporalMode.NONTEMPORAL:
if len(mapCount) > 1:
- raise GException(_("Inconsistent number of maps, please check input data."))
+ raise GException(
+ _("Inconsistent number of maps, please check input data."))
elif temporalMode == TemporalMode.TEMPORAL:
tempManager = TemporalManager()
# these raise GException:
@@ -449,8 +488,14 @@
def Reload(self):
self.EndAnimation()
- color = UserSettings.Get(group='animation', key='bgcolor', subkey='color')
- cpus = UserSettings.Get(group='animation', key='nprocs', subkey='value')
+ color = UserSettings.Get(
+ group='animation',
+ key='bgcolor',
+ subkey='color')
+ cpus = UserSettings.Get(
+ group='animation',
+ key='nprocs',
+ subkey='value')
self.bitmapProvider.Load(nprocs=cpus, bgcolor=color, force=True)
self.EndAnimation()
@@ -477,7 +522,8 @@
timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
frameCount = len(timeLabels)
else:
- frameCount = self.animationData[0].mapCount # should be the same for all
+ frameCount = self.animationData[
+ 0].mapCount # should be the same for all
animWinSize = []
animWinPos = []
@@ -492,11 +538,19 @@
animWinIndex.append(i)
images = []
- busy = wx.BusyInfo(message=_("Preparing export, please wait..."), parent=self.frame)
+ busy = wx.BusyInfo(
+ message=_("Preparing export, please wait..."),
+ parent=self.frame)
wx.Yield()
lastBitmaps = {}
- fgcolor = UserSettings.Get(group='animation', key='font', subkey='fgcolor')
- bgcolor = UserSettings.Get(group='animation', key='font', subkey='bgcolor')
+ fgcolor = UserSettings.Get(
+ group='animation',
+ key='font',
+ subkey='fgcolor')
+ bgcolor = UserSettings.Get(
+ group='animation',
+ key='font',
+ subkey='bgcolor')
for frameIndex in range(frameCount):
image = wx.EmptyImage(*size)
image.Replace(0, 0, 0, 255, 255, 255)
@@ -514,7 +568,7 @@
else:
bitmap = self.bitmapProvider.GetBitmap(frameId)
lastBitmaps[i] = bitmap
-
+
im = wx.ImageFromBitmap(lastBitmaps[i])
# add legend if used
@@ -523,7 +577,8 @@
legendBitmap = self.bitmapProvider.LoadOverlay(legend)
x, y = self.mapwindows[i].GetOverlayPos()
legImage = wx.ImageFromBitmap(legendBitmap)
- # not so nice result, can we handle the transparency otherwise?
+ # not so nice result, can we handle the transparency
+ # otherwise?
legImage.ConvertAlphaToMask()
im.Paste(legImage, x, y)
@@ -540,19 +595,24 @@
elif decoration['name'] == 'time':
timeLabel = timeLabels[frameIndex]
if timeLabel[1]: # interval
- text = _("%(from)s %(dash)s %(to)s") % \
- {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
+ text = _("%(from)s %(dash)s %(to)s") % {
+ 'from': timeLabel[0],
+ 'dash': u"\u2013", 'to': timeLabel[1]}
else:
if self.temporalManager.GetTemporalType() == TemporalType.ABSOLUTE:
text = timeLabel[0]
else:
text = _("%(start)s %(unit)s") % \
- {'start': timeLabel[0], 'unit': timeLabel[2]}
+ {'start': timeLabel[0], 'unit': timeLabel[2]}
- decImage = RenderText(text, decoration['font'], bgcolor, fgcolor).ConvertToImage()
+ decImage = RenderText(
+ text, decoration['font'],
+ bgcolor, fgcolor).ConvertToImage()
elif decoration['name'] == 'text':
text = decoration['text']
- decImage = RenderText(text, decoration['font'], bgcolor, fgcolor).ConvertToImage()
+ decImage = RenderText(
+ text, decoration['font'],
+ bgcolor, fgcolor).ConvertToImage()
image.Paste(decImage, x, y)
@@ -566,8 +626,11 @@
wx.Yield()
try:
if exportInfo['method'] == 'sequence':
- filename = os.path.join(exportInfo['directory'],
- exportInfo['prefix'] + '.' + exportInfo['format'].lower())
+ filename = os.path.join(
+ exportInfo['directory'],
+ exportInfo['prefix'] +
+ '.' +
+ exportInfo['format'].lower())
writeIms(filename=filename, images=pilImages)
elif exportInfo['method'] == 'gif':
writeGif(filename=exportInfo['file'], images=pilImages,
Modified: grass/trunk/gui/wxpython/animation/data.py
===================================================================
--- grass/trunk/gui/wxpython/animation/data.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/data.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -32,6 +32,7 @@
class AnimationData(object):
+
def __init__(self):
self._name = None
self._windowIndex = 0
@@ -209,17 +210,22 @@
def GetZoomRegionValue(self):
return self._zoomRegionValue
- zoomRegionValue = property(fset=SetZoomRegionValue, fget=GetZoomRegionValue)
+ zoomRegionValue = property(
+ fset=SetZoomRegionValue,
+ fget=GetZoomRegionValue)
def GetRegions(self, width, height):
self._computeRegions(width, height, self._mapCount, self._startRegion,
self._endRegion, self._zoomRegionValue)
return self._regions
- def _computeRegions(self, width, height, count, startRegion, endRegion=None, zoomValue=None):
+ def _computeRegions(
+ self, width, height, count, startRegion, endRegion=None,
+ zoomValue=None):
"""Computes regions based on start region and end region or zoom value
for each of the animation frames."""
- currRegion = dict(gcore.region()) # cast to dict, otherwise deepcopy error
+ currRegion = dict(
+ gcore.region()) # cast to dict, otherwise deepcopy error
del currRegion['cells']
del currRegion['cols']
del currRegion['rows']
@@ -237,15 +243,24 @@
self._regions = regions
return
- startRegionDict = parse_key_val(gcore.read_command('g.region', flags='gu',
- region=startRegion),
- val_type=float)
+ startRegionDict = parse_key_val(
+ gcore.read_command(
+ 'g.region',
+ flags='gu',
+ region=startRegion),
+ val_type=float)
if endRegion:
- endRegionDict = parse_key_val(gcore.read_command('g.region', flags='gu',
- region=endRegion),
- val_type=float)
+ endRegionDict = parse_key_val(
+ gcore.read_command(
+ 'g.region',
+ flags='gu',
+ region=endRegion),
+ val_type=float)
for key in ('n', 's', 'e', 'w'):
- values = interpolate(startRegionDict[key], endRegionDict[key], self._mapCount)
+ values = interpolate(
+ startRegionDict[key],
+ endRegionDict[key],
+ self._mapCount)
for value, region in zip(values, regions):
region[key] = value
@@ -259,7 +274,7 @@
# handle cases when north < south and similarly EW
if regions[i]['n'] < regions[i]['s'] or \
regions[i]['e'] < regions[i]['w']:
- regions[i] = regions[i - 1]
+ regions[i] = regions[i - 1]
for region in regions:
mapwidth = abs(region['e'] - region['w'])
@@ -276,6 +291,7 @@
class AnimLayer(Layer):
"""Animation layer allows adding either space-time dataset
or series of maps."""
+
def __init__(self):
Layer.__init__(self)
self._mapTypes.extend(['strds', 'stvds', 'str3ds'])
@@ -284,7 +300,8 @@
def SetName(self, name):
if not self.hidden:
if self._mapType is None:
- raise ValueError("To set layer name, the type of layer must be specified.")
+ raise ValueError(
+ "To set layer name, the type of layer must be specified.")
if self._mapType in ('strds', 'stvds', 'str3ds'):
try:
name = validateTimeseriesName(name, self._mapType)
Modified: grass/trunk/gui/wxpython/animation/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/animation/dialogs.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/dialogs.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -48,6 +48,7 @@
class SpeedDialog(wx.Dialog):
+
def __init__(self, parent, title=_("Adjust speed of animation"),
temporalMode=None, minimumDuration=0, timeGranularity=None,
initialSpeed=200):
@@ -75,7 +76,9 @@
def GetTimeGranularity(self):
return self._timeGranularity
- timeGranularity = property(fset=SetTimeGranularity, fget=GetTimeGranularity)
+ timeGranularity = property(
+ fset=SetTimeGranularity,
+ fget=GetTimeGranularity)
def SetTemporalMode(self, mode):
self._temporalMode = mode
@@ -97,20 +100,37 @@
box = wx.StaticBoxSizer(self.nontemporalBox, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
- labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Frame duration:"))
+ labelDuration = wx.StaticText(
+ self, id=wx.ID_ANY, label=_("Frame duration:"))
labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
- self.spinDuration = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
- max=10000, initial=self.defaultSpeed)
+ self.spinDuration = wx.SpinCtrl(
+ self,
+ id=wx.ID_ANY,
+ min=self.minimumDuration,
+ max=10000,
+ initial=self.defaultSpeed)
# TODO total time
- gridSizer.Add(item=labelDuration, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
- gridSizer.Add(item=self.spinDuration, pos=(0, 1), flag = wx.ALIGN_CENTER)
- gridSizer.Add(item=labelUnits, pos=(0, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ gridSizer.Add(
+ item=labelDuration, pos=(0, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ gridSizer.Add(item=self.spinDuration, pos=(0, 1), flag=wx.ALIGN_CENTER)
+ gridSizer.Add(
+ item=labelUnits, pos=(0, 2),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
gridSizer.AddGrowableCol(0)
- box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
+ box.Add(
+ item=gridSizer,
+ proportion=1,
+ border=5,
+ flag=wx.ALL | wx.EXPAND)
self.nontemporalSizer = gridSizer
- mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+ mainSizer.Add(
+ item=box,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
#
# temporal mode
#
@@ -119,25 +139,45 @@
box = wx.StaticBoxSizer(self.temporalBox, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
- labelTimeUnit = wx.StaticText(self, id=wx.ID_ANY, label=_("Time unit:"))
- labelDuration = wx.StaticText(self, id=wx.ID_ANY, label=_("Duration of time unit:"))
+ labelTimeUnit = wx.StaticText(
+ self, id=wx.ID_ANY, label=_("Time unit:"))
+ labelDuration = wx.StaticText(
+ self, id=wx.ID_ANY, label=_("Duration of time unit:"))
labelUnits = wx.StaticText(self, id=wx.ID_ANY, label=_("ms"))
- self.spinDurationTemp = wx.SpinCtrl(self, id=wx.ID_ANY, min=self.minimumDuration,
- max=10000, initial=self.defaultSpeed)
+ self.spinDurationTemp = wx.SpinCtrl(
+ self, id=wx.ID_ANY, min=self.minimumDuration, max=10000,
+ initial=self.defaultSpeed)
self.choiceUnits = wx.Choice(self, id=wx.ID_ANY)
# TODO total time
- gridSizer.Add(item=labelTimeUnit, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
- gridSizer.Add(item=self.choiceUnits, pos=(0, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
- gridSizer.Add(item=labelDuration, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
- gridSizer.Add(item=self.spinDurationTemp, pos=(1, 1), flag = wx.ALIGN_CENTER | wx.EXPAND)
- gridSizer.Add(item=labelUnits, pos=(1, 2), flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ gridSizer.Add(
+ item=labelTimeUnit, pos=(0, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ gridSizer.Add(item=self.choiceUnits, pos=(0, 1),
+ flag=wx.ALIGN_CENTER | wx.EXPAND)
+ gridSizer.Add(
+ item=labelDuration, pos=(1, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ gridSizer.Add(
+ item=self.spinDurationTemp, pos=(
+ 1, 1), flag=wx.ALIGN_CENTER | wx.EXPAND)
+ gridSizer.Add(
+ item=labelUnits, pos=(1, 2),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
gridSizer.AddGrowableCol(1)
self.temporalSizer = gridSizer
- box.Add(item=gridSizer, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
- mainSizer.Add(item=box, proportion=0, flag=wx.EXPAND | wx.ALL, border=5)
+ box.Add(
+ item=gridSizer,
+ proportion=1,
+ border=5,
+ flag=wx.ALL | wx.EXPAND)
+ mainSizer.Add(
+ item=box,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.btnOk = wx.Button(self, wx.ID_OK)
self.btnApply = wx.Button(self, wx.ID_APPLY)
@@ -162,7 +202,8 @@
mainSizer.Fit(self)
def _setTemporalMode(self):
- self.nontemporalBox.Enable(self.temporalMode == TemporalMode.NONTEMPORAL)
+ self.nontemporalBox.Enable(
+ self.temporalMode == TemporalMode.NONTEMPORAL)
self.temporalBox.Enable(self.temporalMode == TemporalMode.TEMPORAL)
for child in self.temporalSizer.GetChildren():
child.GetWindow().Enable(self.temporalMode == TemporalMode.TEMPORAL)
@@ -172,7 +213,13 @@
self.Layout()
def _fillUnitChoice(self, choiceWidget):
- timeUnitsChoice = [_("year"), _("month"), _("day"), _("hour"), _("minute"), _("second")]
+ timeUnitsChoice = [
+ _("year"),
+ _("month"),
+ _("day"),
+ _("hour"),
+ _("minute"),
+ _("second")]
timeUnits = ["years", "months", "days", "hours", "minutes", "seconds"]
for item, cdata in zip(timeUnitsChoice, timeUnits):
choiceWidget.Append(item, cdata)
@@ -236,7 +283,8 @@
ms = value * seconds2 / float(seconds1)
# minimumDuration set to 0, too restrictive
if ms < self.minimumDuration:
- GMessage(parent=self, message=_("Animation speed is too high."))
+ GMessage(parent=self, message=_(
+ "Animation speed is too high."))
return
self.lastAppliedValueTemp = self.spinDurationTemp.GetValue()
else:
@@ -267,6 +315,7 @@
class InputDialog(wx.Dialog):
+
def __init__(self, parent, mode, animationData):
wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
@@ -284,9 +333,19 @@
def _layout(self):
self.notebook = wx.Notebook(parent=self, style=wx.BK_DEFAULT)
sizer = wx.BoxSizer(wx.VERTICAL)
- self.notebook.AddPage(self._createGeneralPage(self.notebook), _("General"))
- self.notebook.AddPage(self._createAdvancedPage(self.notebook), _("Advanced"))
- sizer.Add(self.notebook, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+ self.notebook.AddPage(
+ self._createGeneralPage(
+ self.notebook),
+ _("General"))
+ self.notebook.AddPage(
+ self._createAdvancedPage(
+ self.notebook),
+ _("Advanced"))
+ sizer.Add(
+ self.notebook,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=3)
# buttons
self.btnOk = wx.Button(self, wx.ID_OK)
@@ -308,17 +367,24 @@
panel = wx.Panel(parent=parent)
mainSizer = wx.BoxSizer(wx.VERTICAL)
- self.windowChoice = wx.Choice(panel, id=wx.ID_ANY,
- choices=[_("top left"), _("top right"),
- _("bottom left"), _("bottom right")])
+ self.windowChoice = wx.Choice(
+ panel,
+ id=wx.ID_ANY,
+ choices=[
+ _("top left"),
+ _("top right"),
+ _("bottom left"),
+ _("bottom right")])
self.windowChoice.SetSelection(self.animationData.windowIndex)
- self.nameCtrl = wx.TextCtrl(panel, id=wx.ID_ANY, value=self.animationData.name)
+ self.nameCtrl = wx.TextCtrl(
+ panel, id=wx.ID_ANY, value=self.animationData.name)
self.nDChoice = wx.Choice(panel, id=wx.ID_ANY)
mode = self.animationData.viewMode
index = 0
- for i, (viewMode, viewModeName) in enumerate(self.animationData.viewModes):
+ for i, (viewMode, viewModeName) in enumerate(
+ self.animationData.viewModes):
self.nDChoice.Append(viewModeName, clientData=viewMode)
if mode == viewMode:
index = i
@@ -328,28 +394,61 @@
self.nDChoice.Bind(wx.EVT_CHOICE, self.OnViewMode)
gridSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
- gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Name:")),
- flag=wx.ALIGN_CENTER_VERTICAL)
+ gridSizer.Add(
+ item=wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Name:")),
+ flag=wx.ALIGN_CENTER_VERTICAL)
gridSizer.Add(item=self.nameCtrl, proportion=1, flag=wx.EXPAND)
- gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Window position:")),
- flag=wx.ALIGN_CENTER_VERTICAL)
- gridSizer.Add(item=self.windowChoice, proportion=1, flag=wx.ALIGN_RIGHT)
- gridSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("View mode:")),
- flag=wx.ALIGN_CENTER_VERTICAL)
+ gridSizer.Add(
+ item=wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Window position:")),
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ gridSizer.Add(
+ item=self.windowChoice,
+ proportion=1,
+ flag=wx.ALIGN_RIGHT)
+ gridSizer.Add(
+ item=wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("View mode:")),
+ flag=wx.ALIGN_CENTER_VERTICAL)
gridSizer.Add(item=self.nDChoice, proportion=1, flag=wx.ALIGN_RIGHT)
gridSizer.AddGrowableCol(0, 1)
gridSizer.AddGrowableCol(1, 1)
- mainSizer.Add(item=gridSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
- label = _("For 3D animation, please select only one space-time dataset\n"
- "or one series of map layers.")
+ mainSizer.Add(
+ item=gridSizer,
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
+ label = _(
+ "For 3D animation, please select only one space-time dataset\n"
+ "or one series of map layers.")
self.warning3DLayers = wx.StaticText(panel, label=label)
- self.warning3DLayers.SetForegroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
- mainSizer.Add(item=self.warning3DLayers, proportion=0, flag=wx.EXPAND | wx.LEFT, border=5)
+ self.warning3DLayers.SetForegroundColour(
+ wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ mainSizer.Add(
+ item=self.warning3DLayers,
+ proportion=0,
+ flag=wx.EXPAND | wx.LEFT,
+ border=5)
self.dataPanel = self._createDataPanel(panel)
self.threeDPanel = self._create3DPanel(panel)
- mainSizer.Add(item=self.dataPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=3)
- mainSizer.Add(item=self.threeDPanel, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+ mainSizer.Add(
+ item=self.dataPanel,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
+ mainSizer.Add(
+ item=self.threeDPanel,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
panel.SetSizer(mainSizer)
mainSizer.Fit(panel)
@@ -364,7 +463,11 @@
layerList=self._layerList,
modal=True)
self.simpleLmgr.SetMinSize((globalvar.DIALOG_GSELECT_SIZE[0], 80))
- slmgrSizer.Add(self.simpleLmgr, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ slmgrSizer.Add(
+ self.simpleLmgr,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.legend = wx.CheckBox(panel, label=_("Show raster legend"))
self.legend.SetValue(bool(self.animationData.legendCmd))
@@ -375,7 +478,11 @@
hbox = wx.BoxSizer(wx.HORIZONTAL)
hbox.Add(item=self.legend, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
hbox.Add(item=self.legendBtn, proportion=0, flag=wx.LEFT, border=5)
- slmgrSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+ slmgrSizer.Add(
+ item=hbox,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
panel.SetSizerAndFit(slmgrSizer)
panel.SetAutoLayout(True)
@@ -389,29 +496,48 @@
dataBoxSizer = wx.StaticBoxSizer(dataStBox, wx.VERTICAL)
# workspace file
- self.fileSelector = \
- filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE,
- labelText=_("Workspace file:"),
- dialogTitle=_("Choose workspace file to "
- "import 3D view parameters"),
- buttonText=_('Browse'),
- startDirectory=os.getcwd(), fileMode=0,
- fileMask="GRASS Workspace File (*.gxw)|*.gxw")
+ self.fileSelector = filebrowse.FileBrowseButton(
+ parent=panel,
+ id=wx.ID_ANY,
+ size=globalvar.DIALOG_GSELECT_SIZE,
+ labelText=_("Workspace file:"),
+ dialogTitle=_(
+ "Choose workspace file to "
+ "import 3D view parameters"),
+ buttonText=_('Browse'),
+ startDirectory=os.getcwd(),
+ fileMode=0,
+ fileMask="GRASS Workspace File (*.gxw)|*.gxw")
if self.animationData.workspaceFile:
self.fileSelector.SetValue(self.animationData.workspaceFile)
- self.paramLabel = wx.StaticText(panel, wx.ID_ANY, label=_("Parameter for animation:"))
- self.paramChoice = wx.Choice(panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters)
+ self.paramLabel = wx.StaticText(
+ panel, wx.ID_ANY, label=_("Parameter for animation:"))
+ self.paramChoice = wx.Choice(
+ panel, id=wx.ID_ANY, choices=self.animationData.nvizParameters)
self.paramChoice.SetStringSelection(self.animationData.nvizParameter)
hbox = wx.BoxSizer(wx.HORIZONTAL)
- hbox.Add(item=self.fileSelector, proportion=1, flag=wx.EXPAND | wx.ALIGN_CENTER)
- dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+ hbox.Add(
+ item=self.fileSelector,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALIGN_CENTER)
+ dataBoxSizer.Add(
+ item=hbox,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
hbox = wx.BoxSizer(wx.HORIZONTAL)
- hbox.Add(item=self.paramLabel, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
+ hbox.Add(
+ item=self.paramLabel,
+ proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL)
hbox.Add(item=self.paramChoice, proportion=1, flag=wx.EXPAND)
- dataBoxSizer.Add(item=hbox, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+ dataBoxSizer.Add(
+ item=hbox,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
panel.SetSizerAndFit(dataBoxSizer)
panel.SetAutoLayout(True)
@@ -422,7 +548,9 @@
panel = wx.Panel(parent=parent)
mainSizer = wx.BoxSizer(wx.VERTICAL)
- box = wx.StaticBox(parent=panel, label=" %s " % _("Animate region change (2D view only)"))
+ box = wx.StaticBox(
+ parent=panel, label=" %s " %
+ _("Animate region change (2D view only)"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
@@ -431,12 +559,17 @@
self.stRegion = Select(parent=panel, type='region', size=(200, -1))
if self.animationData.startRegion:
self.stRegion.SetValue(self.animationData.startRegion)
- gridSizer.Add(self.stRegion, pos=(0, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+ gridSizer.Add(
+ self.stRegion, pos=(0, 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
- self.endRegRadio = wx.RadioButton(panel, label=_("End region:"), style=wx.RB_GROUP)
+ self.endRegRadio = wx.RadioButton(
+ panel, label=_("End region:"), style=wx.RB_GROUP)
gridSizer.Add(self.endRegRadio, pos=(1, 0), flag=wx.EXPAND)
self.endRegion = Select(parent=panel, type='region', size=(200, -1))
- gridSizer.Add(self.endRegion, pos=(1, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+ gridSizer.Add(
+ self.endRegion, pos=(1, 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
self.zoomRadio = wx.RadioButton(panel, label=_("Zoom value:"))
self.zoomRadio.SetToolTipString(_("N-S/E-W distances in map units used to "
"gradually reduce region."))
@@ -451,7 +584,9 @@
zoomSizer.Add(wx.StaticText(panel, label=_("E-W:")), proportion=0,
flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT, border=3)
zoomSizer.Add(self.zoomEW, proportion=1, flag=wx.LEFT, border=3)
- gridSizer.Add(zoomSizer, pos=(2, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+ gridSizer.Add(
+ zoomSizer, pos=(2, 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
if self.animationData.endRegion:
self.endRegRadio.SetValue(True)
self.zoomRadio.SetValue(False)
@@ -463,8 +598,12 @@
self.zoomNS.SetValue(str(zoom[0]))
self.zoomEW.SetValue(str(zoom[1]))
- self.endRegRadio.Bind(wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets())
- self.zoomRadio.Bind(wx.EVT_RADIOBUTTON, lambda evt: self._enableRegionWidgets())
+ self.endRegRadio.Bind(
+ wx.EVT_RADIOBUTTON,
+ lambda evt: self._enableRegionWidgets())
+ self.zoomRadio.Bind(
+ wx.EVT_RADIOBUTTON,
+ lambda evt: self._enableRegionWidgets())
self._enableRegionWidgets()
gridSizer.AddGrowableCol(1)
@@ -512,8 +651,8 @@
if self._tmpLegendCmd or self.animationData.legendCmd:
return
cmd = ['d.legend', 'at=5,50,2,5']
- GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
- completed=(self.GetOptData, '', ''))
+ GUI(parent=self, modal=True).ParseCommand(
+ cmd=cmd, completed=(self.GetOptData, '', ''))
def OnLegendProperties(self, event):
"""Set options for legend"""
@@ -524,8 +663,8 @@
else:
cmd = ['d.legend', 'at=5,50,2,5']
- GUI(parent=self, modal=True).ParseCommand(cmd=cmd,
- completed=(self.GetOptData, '', ''))
+ GUI(parent=self, modal=True).ParseCommand(
+ cmd=cmd, completed=(self.GetOptData, '', ''))
def GetOptData(self, dcmd, layer, params, propwin):
"""Process decoration layer data"""
@@ -583,8 +722,9 @@
self.animationData.endRegion = self.endRegion.GetValue()
self.animationData.zoomRegionValue = None
else:
- self.animationData.zoomRegionValue = (float(self.zoomNS.GetValue()),
- float(self.zoomEW.GetValue()))
+ self.animationData.zoomRegionValue = (
+ float(self.zoomNS.GetValue()),
+ float(self.zoomEW.GetValue()))
self.animationData.endRegion = None
else:
self.animationData.startRegion = None
@@ -596,10 +736,14 @@
self._update()
self.EndModal(wx.ID_OK)
except (GException, ValueError, IOError) as e:
- GError(message=str(e), showTraceback=False, caption=_("Invalid input"))
+ GError(
+ message=str(e),
+ showTraceback=False,
+ caption=_("Invalid input"))
class EditDialog(wx.Dialog):
+
def __init__(self, parent, evalFunction, animationData, maxAnimations):
wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY,
style=wx.DEFAULT_DIALOG_STYLE)
@@ -613,13 +757,19 @@
def _layout(self):
mainSizer = wx.BoxSizer(wx.VERTICAL)
- box = wx.StaticBox (parent=self, id=wx.ID_ANY, label=" %s " % _("List of animations"))
+ box = wx.StaticBox(
+ parent=self,
+ id=wx.ID_ANY,
+ label=" %s " %
+ _("List of animations"))
sizer = wx.StaticBoxSizer(box, wx.VERTICAL)
- gridBagSizer = wx.GridBagSizer (hgap=5, vgap=5)
+ gridBagSizer = wx.GridBagSizer(hgap=5, vgap=5)
gridBagSizer.AddGrowableCol(0)
# gridBagSizer.AddGrowableCol(1,1)
- self.listbox = wx.ListBox(self, id=wx.ID_ANY, choices=[], style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
+ self.listbox = wx.ListBox(
+ self, id=wx.ID_ANY, choices=[],
+ style=wx.LB_SINGLE | wx.LB_NEEDED_SB)
self.listbox.Bind(wx.EVT_LISTBOX_DCLICK, self.OnEdit)
self.addButton = wx.Button(self, id=wx.ID_ANY, label=_("Add"))
@@ -631,15 +781,19 @@
self._updateListBox()
- gridBagSizer.Add(self.listbox, pos=(0, 0), span = (3, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ gridBagSizer.Add(self.listbox, pos=(0, 0), span=(3, 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
gridBagSizer.Add(self.addButton, pos=(0, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
gridBagSizer.Add(self.editButton, pos=(1, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
gridBagSizer.Add(self.removeButton, pos=(2, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
- sizer.Add(gridBagSizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=5)
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ sizer.Add(
+ gridBagSizer,
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
mainSizer.Add(item=sizer, proportion=0,
flag=wx.EXPAND | wx.ALL, border=5)
@@ -677,7 +831,10 @@
def OnAdd(self, event):
windowIndex = self._getNextIndex()
if windowIndex is None:
- GMessage(self, message=_("Maximum number of animations is %d.") % self.maxAnimations)
+ GMessage(
+ self,
+ message=_("Maximum number of animations is %d.") %
+ self.maxAnimations)
return
animData = AnimationData()
# number of active animations
@@ -724,8 +881,10 @@
def OnOk(self, event):
indices = set([anim.windowIndex for anim in self.animationData])
if len(indices) != len(self.animationData):
- GError(parent=self, message=_("More animations are using one window."
- " Please select different window for each animation."))
+ GError(
+ parent=self, message=_(
+ "More animations are using one window."
+ " Please select different window for each animation."))
return
try:
temporalMode, tempManager = self.eval(self.animationData)
@@ -738,9 +897,14 @@
class ExportDialog(wx.Dialog):
+
def __init__(self, parent, temporal, timeTick):
- wx.Dialog.__init__(self, parent=parent, id=wx.ID_ANY, title=_("Export animation"),
- style=wx.DEFAULT_DIALOG_STYLE)
+ wx.Dialog.__init__(
+ self,
+ parent=parent,
+ id=wx.ID_ANY,
+ title=_("Export animation"),
+ style=wx.DEFAULT_DIALOG_STYLE)
self.decorations = []
self.temporal = temporal
@@ -756,8 +920,12 @@
notebook = wx.Notebook(self, id=wx.ID_ANY)
mainSizer = wx.BoxSizer(wx.VERTICAL)
- notebook.AddPage(page=self._createExportFormatPanel(notebook), text=_("Format"))
- notebook.AddPage(page=self._createDecorationsPanel(notebook), text=_("Decorations"))
+ notebook.AddPage(
+ page=self._createExportFormatPanel(notebook),
+ text=_("Format"))
+ notebook.AddPage(
+ page=self._createDecorationsPanel(notebook),
+ text=_("Decorations"))
mainSizer.Add(item=notebook, proportion=0,
flag=wx.EXPAND | wx.ALL | wx.ALIGN_RIGHT, border=5)
@@ -789,8 +957,16 @@
def _createDecorationsPanel(self, notebook):
panel = wx.Panel(notebook, id=wx.ID_ANY)
sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(self._createDecorationsList(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
- sizer.Add(self._createDecorationsProperties(panel), proportion=0, flag=wx.ALL | wx.EXPAND, border=10)
+ sizer.Add(
+ self._createDecorationsList(panel),
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=10)
+ sizer.Add(
+ self._createDecorationsProperties(panel),
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=10)
panel.SetSizer(sizer)
sizer.Fit(panel)
return panel
@@ -805,7 +981,7 @@
self.listbox.Bind(wx.EVT_LISTBOX, self.OnSelectionChanged)
gridBagSizer.Add(self.listbox, pos=(0, 0), span=(4, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
buttonNames = ['time', 'image', 'text']
buttonLabels = [_("Add time stamp"), _("Add image"), _("Add text")]
@@ -813,13 +989,34 @@
for buttonName, buttonLabel in zip(buttonNames, buttonLabels):
if buttonName == 'time' and self.temporal == TemporalMode.NONTEMPORAL:
continue
- btn = wx.Button(panel, id=wx.ID_ANY, name=buttonName, label=buttonLabel)
- btn.Bind(wx.EVT_BUTTON, lambda evt, temp=buttonName: self.OnAddDecoration(evt, temp))
- gridBagSizer.Add(btn, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ btn = wx.Button(
+ panel,
+ id=wx.ID_ANY,
+ name=buttonName,
+ label=buttonLabel)
+ btn.Bind(
+ wx.EVT_BUTTON,
+ lambda evt,
+ temp=buttonName: self.OnAddDecoration(
+ evt,
+ temp))
+ gridBagSizer.Add(
+ btn,
+ pos=(
+ i,
+ 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+ border=0)
i += 1
removeButton = wx.Button(panel, id=wx.ID_ANY, label=_("Remove"))
removeButton.Bind(wx.EVT_BUTTON, self.OnRemove)
- gridBagSizer.Add(removeButton, pos=(i, 1), flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND, border=0)
+ gridBagSizer.Add(
+ removeButton,
+ pos=(
+ i,
+ 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND,
+ border=0)
return gridBagSizer
@@ -828,66 +1025,118 @@
# inform label
self.informBox = wx.BoxSizer(wx.HORIZONTAL)
if self.temporal == TemporalMode.TEMPORAL:
- label = _("Add time stamp, image or text decoration by one of the buttons above.")
+ label = _(
+ "Add time stamp, image or text decoration by one of the buttons above.")
else:
label = _("Add image or text decoration by one of the buttons above.")
label = wx.StaticText(panel, id=wx.ID_ANY, label=label)
label.Wrap(400)
- self.informBox.Add(label, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
- self.hidevbox.Add(self.informBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+ self.informBox.Add(
+ label,
+ proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+ border=5)
+ self.hidevbox.Add(
+ self.informBox,
+ proportion=0,
+ flag=wx.EXPAND | wx.BOTTOM,
+ border=5)
# font
self.fontBox = wx.BoxSizer(wx.HORIZONTAL)
- self.fontBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Font settings:")),
- proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
- self.sampleLabel = wx.StaticText(panel, id=wx.ID_ANY, label=_("Sample text"))
+ self.fontBox.Add(
+ wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Font settings:")),
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+ border=5)
+ self.sampleLabel = wx.StaticText(
+ panel, id=wx.ID_ANY, label=_("Sample text"))
self.fontBox.Add(self.sampleLabel, proportion=1,
flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT, border=5)
fontButton = wx.Button(panel, id=wx.ID_ANY, label=_("Set font"))
fontButton.Bind(wx.EVT_BUTTON, self.OnFont)
- self.fontBox.Add(fontButton, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
- self.hidevbox.Add(self.fontBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+ self.fontBox.Add(
+ fontButton,
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ self.hidevbox.Add(
+ self.fontBox,
+ proportion=0,
+ flag=wx.EXPAND | wx.BOTTOM,
+ border=5)
# image
self.imageBox = wx.BoxSizer(wx.HORIZONTAL)
filetype, ltype = GetImageHandlers(wx.EmptyImage(10, 10))
- self.browse = filebrowse.FileBrowseButton(parent=panel, id=wx.ID_ANY, fileMask=filetype,
- labelText=_("Image file:"),
- dialogTitle=_('Choose image file'),
- buttonText=_('Browse'),
- startDirectory=os.getcwd(), fileMode=wx.FD_OPEN,
- changeCallback=self.OnSetImage)
+ self.browse = filebrowse.FileBrowseButton(
+ parent=panel, id=wx.ID_ANY, fileMask=filetype,
+ labelText=_("Image file:"),
+ dialogTitle=_('Choose image file'),
+ buttonText=_('Browse'),
+ startDirectory=os.getcwd(),
+ fileMode=wx.FD_OPEN, changeCallback=self.OnSetImage)
self.imageBox.Add(self.browse, proportion=1, flag=wx.EXPAND)
- self.hidevbox.Add(self.imageBox, proportion=0, flag=wx.EXPAND | wx.BOTTOM, border=5)
+ self.hidevbox.Add(
+ self.imageBox,
+ proportion=0,
+ flag=wx.EXPAND | wx.BOTTOM,
+ border=5)
# text
self.textBox = wx.BoxSizer(wx.HORIZONTAL)
- self.textBox.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Text:")),
- proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
+ self.textBox.Add(
+ wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Text:")),
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+ border=5)
self.textCtrl = wx.TextCtrl(panel, id=wx.ID_ANY)
self.textCtrl.Bind(wx.EVT_TEXT, self.OnText)
self.textBox.Add(self.textCtrl, proportion=1, flag=wx.EXPAND)
self.hidevbox.Add(self.textBox, proportion=0, flag=wx.EXPAND)
self.posBox = self._positionWidget(panel)
- self.hidevbox.Add(self.posBox, proportion=0, flag=wx.EXPAND | wx.TOP, border=5)
+ self.hidevbox.Add(
+ self.posBox,
+ proportion=0,
+ flag=wx.EXPAND | wx.TOP,
+ border=5)
return self.hidevbox
def _positionWidget(self, panel):
grid = wx.GridBagSizer(vgap=5, hgap=5)
- label = wx.StaticText(panel, id=wx.ID_ANY, label=_("Placement as percentage of"
- " screen coordinates (X: 0, Y: 0 is top left):"))
+ label = wx.StaticText(
+ panel, id=wx.ID_ANY, label=_(
+ "Placement as percentage of"
+ " screen coordinates (X: 0, Y: 0 is top left):"))
label.Wrap(400)
- self.spinX = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
- self.spinY = wx.SpinCtrl(panel, id=wx.ID_ANY, min=0, max=100, initial=10)
- self.spinX.Bind(wx.EVT_SPINCTRL, lambda evt, temp='X': self.OnPosition(evt, temp))
- self.spinY.Bind(wx.EVT_SPINCTRL, lambda evt, temp='Y': self.OnPosition(evt, temp))
+ self.spinX = wx.SpinCtrl(
+ panel, id=wx.ID_ANY, min=0, max=100, initial=10)
+ self.spinY = wx.SpinCtrl(
+ panel, id=wx.ID_ANY, min=0, max=100, initial=10)
+ self.spinX.Bind(
+ wx.EVT_SPINCTRL,
+ lambda evt,
+ temp='X': self.OnPosition(
+ evt,
+ temp))
+ self.spinY.Bind(
+ wx.EVT_SPINCTRL,
+ lambda evt,
+ temp='Y': self.OnPosition(
+ evt,
+ temp))
- grid.Add(label, pos=(0, 0), span = (1, 4), flag = wx.EXPAND)
+ grid.Add(label, pos=(0, 0), span=(1, 4), flag=wx.EXPAND)
grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("X:")), pos=(1, 0),
- flag = wx.ALIGN_CENTER_VERTICAL)
+ flag=wx.ALIGN_CENTER_VERTICAL)
grid.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Y:")), pos=(1, 2),
- flag = wx.ALIGN_CENTER_VERTICAL)
+ flag=wx.ALIGN_CENTER_VERTICAL)
grid.Add(self.spinX, pos=(1, 1))
grid.Add(self.spinY, pos=(1, 3))
@@ -901,12 +1150,28 @@
choices = [_("image sequence"), _("animated GIF"), _("SWF"), _("AVI")]
self.formatChoice = wx.Choice(parent=panel, id=wx.ID_ANY,
choices=choices)
- self.formatChoice.Bind(wx.EVT_CHOICE, lambda event: self.ChangeFormat(event.GetSelection()))
- hSizer.Add(item=wx.StaticText(panel, id=wx.ID_ANY, label=_("Export to:")),
- proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=2)
- hSizer.Add(item=self.formatChoice, proportion=1,
- flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL, border=2)
- borderSizer.Add(item=hSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=3)
+ self.formatChoice.Bind(
+ wx.EVT_CHOICE,
+ lambda event: self.ChangeFormat(
+ event.GetSelection()))
+ hSizer.Add(
+ item=wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Export to:")),
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=2)
+ hSizer.Add(
+ item=self.formatChoice,
+ proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND | wx.ALL,
+ border=2)
+ borderSizer.Add(
+ item=hSizer,
+ proportion=0,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
helpSizer = wx.BoxSizer(wx.HORIZONTAL)
helpSizer.AddStretchSpacer(1)
@@ -917,92 +1182,138 @@
# panel for image sequence
imSeqPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
- prefixLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
- self.prefixCtrl = wx.TextCtrl(imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
- formatLabel = wx.StaticText(imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
+ prefixLabel = wx.StaticText(
+ imSeqPanel, id=wx.ID_ANY, label=_("File prefix:"))
+ self.prefixCtrl = wx.TextCtrl(
+ imSeqPanel, id=wx.ID_ANY, value=_("animation_"))
+ formatLabel = wx.StaticText(
+ imSeqPanel, id=wx.ID_ANY, label=_("File format:"))
imageTypes = ['PNG', 'JPEG', 'GIF', 'TIFF', 'PPM', 'BMP']
self.imSeqFormatChoice = wx.Choice(imSeqPanel, choices=imageTypes)
self.imSeqFormatChoice.SetSelection(0)
- self.dirBrowse = filebrowse.DirBrowseButton(parent=imSeqPanel, id=wx.ID_ANY,
- labelText=_("Directory:"),
- dialogTitle=_("Choose directory for export"),
- buttonText=_("Browse"),
- startDirectory=os.getcwd())
+ self.dirBrowse = filebrowse.DirBrowseButton(
+ parent=imSeqPanel, id=wx.ID_ANY, labelText=_("Directory:"),
+ dialogTitle=_("Choose directory for export"),
+ buttonText=_("Browse"),
+ startDirectory=os.getcwd())
dirGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
- dirGridSizer.Add(prefixLabel, pos=(0, 0), flag = wx.ALIGN_CENTER_VERTICAL)
- dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag = wx.EXPAND)
- dirGridSizer.Add(formatLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
- dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag = wx.EXPAND)
- dirGridSizer.Add(self.dirBrowse, pos=(2, 0), flag = wx.EXPAND, span = (1, 2))
+ dirGridSizer.Add(
+ prefixLabel, pos=(0, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ dirGridSizer.Add(self.prefixCtrl, pos=(0, 1), flag=wx.EXPAND)
+ dirGridSizer.Add(
+ formatLabel, pos=(1, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ dirGridSizer.Add(self.imSeqFormatChoice, pos=(1, 1), flag=wx.EXPAND)
+ dirGridSizer.Add(
+ self.dirBrowse, pos=(
+ 2, 0), flag=wx.EXPAND, span=(
+ 1, 2))
dirGridSizer.AddGrowableCol(1)
imSeqPanel.SetSizer(dirGridSizer)
dirGridSizer.Fit(imSeqPanel)
- self.formatPanelSizer.Add(item=imSeqPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ self.formatPanelSizer.Add(
+ item=imSeqPanel,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.formatPanels.append(imSeqPanel)
# panel for gif
gifPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
- self.gifBrowse = filebrowse.FileBrowseButton(parent=gifPanel, id=wx.ID_ANY,
- fileMask="GIF file (*.gif)|*.gif",
- labelText=_("GIF file:"),
- dialogTitle=_("Choose file to save animation"),
- buttonText=_("Browse"),
- startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
+ self.gifBrowse = filebrowse.FileBrowseButton(
+ parent=gifPanel,
+ id=wx.ID_ANY,
+ fileMask="GIF file (*.gif)|*.gif",
+ labelText=_("GIF file:"),
+ dialogTitle=_("Choose file to save animation"),
+ buttonText=_("Browse"),
+ startDirectory=os.getcwd(),
+ fileMode=wx.FD_SAVE)
gifGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
gifGridSizer.AddGrowableCol(0)
- gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag = wx.EXPAND)
+ gifGridSizer.Add(self.gifBrowse, pos=(0, 0), flag=wx.EXPAND)
gifPanel.SetSizer(gifGridSizer)
gifGridSizer.Fit(gifPanel)
- self.formatPanelSizer.Add(item=gifPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ self.formatPanelSizer.Add(
+ item=gifPanel,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.formatPanels.append(gifPanel)
# panel for swf
swfPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
- self.swfBrowse = filebrowse.FileBrowseButton(parent=swfPanel, id=wx.ID_ANY,
- fileMask="SWF file (*.swf)|*.swf",
- labelText=_("SWF file:"),
- dialogTitle=_("Choose file to save animation"),
- buttonText=_("Browse"),
- startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
+ self.swfBrowse = filebrowse.FileBrowseButton(
+ parent=swfPanel,
+ id=wx.ID_ANY,
+ fileMask="SWF file (*.swf)|*.swf",
+ labelText=_("SWF file:"),
+ dialogTitle=_("Choose file to save animation"),
+ buttonText=_("Browse"),
+ startDirectory=os.getcwd(),
+ fileMode=wx.FD_SAVE)
swfGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
swfGridSizer.AddGrowableCol(0)
- swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag = wx.EXPAND)
+ swfGridSizer.Add(self.swfBrowse, pos=(0, 0), flag=wx.EXPAND)
swfPanel.SetSizer(swfGridSizer)
swfGridSizer.Fit(swfPanel)
- self.formatPanelSizer.Add(item=swfPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ self.formatPanelSizer.Add(
+ item=swfPanel,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.formatPanels.append(swfPanel)
# panel for avi
aviPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
ffmpeg = gcore.find_program('ffmpeg', '--help')
if not ffmpeg:
- warning = _("Program 'ffmpeg' was not found.\nPlease install it first "
- "and make sure\nit's in the PATH variable.")
+ warning = _(
+ "Program 'ffmpeg' was not found.\nPlease install it first "
+ "and make sure\nit's in the PATH variable.")
warningLabel = wx.StaticText(parent=aviPanel, label=warning)
warningLabel.SetForegroundColour(wx.RED)
- self.aviBrowse = filebrowse.FileBrowseButton(parent=aviPanel, id=wx.ID_ANY,
- fileMask="AVI file (*.avi)|*.avi",
- labelText=_("AVI file:"),
- dialogTitle=_("Choose file to save animation"),
- buttonText=_("Browse"),
- startDirectory=os.getcwd(), fileMode=wx.FD_SAVE)
- encodingLabel = wx.StaticText(parent=aviPanel, id=wx.ID_ANY, label=_("Video codec:"))
- self.encodingText = wx.TextCtrl(parent=aviPanel, id=wx.ID_ANY, value='mpeg4')
- optionsLabel = wx.StaticText(parent=aviPanel, label=_("Additional options:"))
+ self.aviBrowse = filebrowse.FileBrowseButton(
+ parent=aviPanel,
+ id=wx.ID_ANY,
+ fileMask="AVI file (*.avi)|*.avi",
+ labelText=_("AVI file:"),
+ dialogTitle=_("Choose file to save animation"),
+ buttonText=_("Browse"),
+ startDirectory=os.getcwd(),
+ fileMode=wx.FD_SAVE)
+ encodingLabel = wx.StaticText(
+ parent=aviPanel,
+ id=wx.ID_ANY,
+ label=_("Video codec:"))
+ self.encodingText = wx.TextCtrl(
+ parent=aviPanel, id=wx.ID_ANY, value='mpeg4')
+ optionsLabel = wx.StaticText(
+ parent=aviPanel, label=_("Additional options:"))
self.optionsText = wx.TextCtrl(parent=aviPanel)
- self.optionsText.SetToolTipString(_("Consider adding '-sameq' or '-qscale 1' "
- "if not satisfied with video quality. "
- "Options depend on ffmpeg version."))
+ self.optionsText.SetToolTipString(
+ _(
+ "Consider adding '-sameq' or '-qscale 1' "
+ "if not satisfied with video quality. "
+ "Options depend on ffmpeg version."))
aviGridSizer = wx.GridBagSizer(hgap=5, vgap=5)
- aviGridSizer.Add(self.aviBrowse, pos=(0, 0), span = (1, 2), flag = wx.EXPAND)
- aviGridSizer.Add(encodingLabel, pos=(1, 0), flag = wx.ALIGN_CENTER_VERTICAL)
- aviGridSizer.Add(self.encodingText, pos=(1, 1), flag = wx.EXPAND)
- aviGridSizer.Add(optionsLabel, pos=(2, 0), flag=wx.ALIGN_CENTER_VERTICAL)
+ aviGridSizer.Add(
+ self.aviBrowse, pos=(
+ 0, 0), span=(
+ 1, 2), flag=wx.EXPAND)
+ aviGridSizer.Add(
+ encodingLabel, pos=(1, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ aviGridSizer.Add(self.encodingText, pos=(1, 1), flag=wx.EXPAND)
+ aviGridSizer.Add(
+ optionsLabel, pos=(2, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL)
aviGridSizer.Add(self.optionsText, pos=(2, 1), flag=wx.EXPAND)
if not ffmpeg:
aviGridSizer.Add(warningLabel, pos=(3, 0), span=(1, 2),
@@ -1012,14 +1323,28 @@
aviPanel.SetSizer(aviGridSizer)
aviGridSizer.Fit(aviPanel)
- self.formatPanelSizer.Add(item=aviPanel, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ self.formatPanelSizer.Add(
+ item=aviPanel,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
self.formatPanels.append(aviPanel)
fpsSizer = wx.BoxSizer(wx.HORIZONTAL)
fps = 1000 / self.timeTick
- fpsSizer.Add(wx.StaticText(panel, id=wx.ID_ANY, label=_("Current frame rate: %.2f fps") % fps),
- proportion=1, flag=wx.EXPAND)
- borderSizer.Add(fpsSizer, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ fpsSizer.Add(
+ wx.StaticText(
+ panel,
+ id=wx.ID_ANY,
+ label=_("Current frame rate: %.2f fps") %
+ fps),
+ proportion=1,
+ flag=wx.EXPAND)
+ borderSizer.Add(
+ fpsSizer,
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
panel.SetSizer(borderSizer)
borderSizer.Fit(panel)
@@ -1078,7 +1403,13 @@
imageInfo = {'name': name, 'file': '', 'pos': [10, 10]}
self.decorations.append(imageInfo)
elif name == 'text':
- textInfo = {'name': name, 'font': self.GetFont(), 'text': '', 'pos': [10, 10]}
+ textInfo = {
+ 'name': name,
+ 'font': self.GetFont(),
+ 'text': '',
+ 'pos': [
+ 10,
+ 10]}
self.decorations.append(textInfo)
self._updateListBox()
@@ -1135,18 +1466,26 @@
if decor['name'] == 'image':
if not os.path.exists(decor['file']):
if decor['file']:
- GError(parent=self, message=_("File %s not found.") % decor['file'])
+ GError(
+ parent=self,
+ message=_("File %s not found.") %
+ decor['file'])
else:
- GError(parent=self, message=_("Decoration image file is missing."))
+ GError(parent=self,
+ message=_("Decoration image file is missing."))
return
if self.formatChoice.GetSelection() == 0:
name = self.dirBrowse.GetValue()
if not os.path.exists(name):
if name:
- GError(parent=self, message=_("Directory %s not found.") % name)
+ GError(
+ parent=self,
+ message=_("Directory %s not found.") %
+ name)
else:
- GError(parent=self, message=_("Export directory is missing."))
+ GError(parent=self, message=_(
+ "Export directory is missing."))
return
elif self.formatChoice.GetSelection() == 1:
if not self.gifBrowse.GetValue():
@@ -1191,7 +1530,10 @@
def _updateListBox(self):
self.listbox.Clear()
- names = {'time': _("Time stamp"), 'image': _("Image"), 'text': _("Text")}
+ names = {
+ 'time': _("Time stamp"),
+ 'image': _("Image"),
+ 'text': _("Text")}
for decor in self.decorations:
self.listbox.Append(names[decor['name']], clientData=decor)
@@ -1208,11 +1550,13 @@
"""Simple layer manager for animation tool.
Allows adding space-time dataset or series of maps.
"""
+
def __init__(self, parent, layerList,
lmgrStyle=SIMPLE_LMGR_RASTER | SIMPLE_LMGR_VECTOR |
SIMPLE_LMGR_TB_TOP | SIMPLE_LMGR_STDS,
toolbarCls=AnimSimpleLmgrToolbar, modal=True):
- SimpleLayerManager.__init__(self, parent, layerList, lmgrStyle, toolbarCls, modal)
+ SimpleLayerManager.__init__(
+ self, parent, layerList, lmgrStyle, toolbarCls, modal)
self._3dActivated = False
def OnAddStds(self, event):
@@ -1225,7 +1569,8 @@
event.Skip()
def SetStdsProperties(self, layer):
- dlg = AddTemporalLayerDialog(parent=self, layer=layer, volume=self._3dActivated)
+ dlg = AddTemporalLayerDialog(
+ parent=self, layer=layer, volume=self._3dActivated)
# first get hidden property, it's altered afterwards
hidden = layer.hidden
dlg.CenterOnParent()
@@ -1235,7 +1580,9 @@
signal = self.layerAdded
else:
signal = self.cmdChanged
- signal.emit(index=self._layerList.GetLayerIndex(layer), layer=layer)
+ signal.emit(
+ index=self._layerList.GetLayerIndex(layer),
+ layer=layer)
else:
if hidden:
self._layerList.RemoveLayer(layer)
@@ -1246,9 +1593,8 @@
def _layerChangeProperties(self, layer):
"""Opens new module dialog or recycles it."""
if not hasattr(layer, 'maps'):
- GUI(parent=self, giface=None,
- modal=self._modal).ParseCommand(cmd=layer.cmd,
- completed=(self.GetOptData, layer, ''))
+ GUI(parent=self, giface=None, modal=self._modal).ParseCommand(
+ cmd=layer.cmd, completed=(self.GetOptData, layer, ''))
else:
self.SetStdsProperties(layer)
@@ -1261,6 +1607,7 @@
class AddTemporalLayerDialog(wx.Dialog):
"""Dialog for adding space-time dataset/ map series."""
+
def __init__(self, parent, layer, volume=False,
title=_("Add space-time dataset layer")):
wx.Dialog.__init__(self, parent=parent, title=title)
@@ -1271,12 +1618,19 @@
self._cmd = None
self.tselect = Select(parent=self, type='strds')
- iconTheme = UserSettings.Get(group='appearance', key='iconTheme', subkey='type')
- bitmapPath = os.path.join(globalvar.ICONDIR, iconTheme, 'layer-open.png')
+ iconTheme = UserSettings.Get(
+ group='appearance',
+ key='iconTheme',
+ subkey='type')
+ bitmapPath = os.path.join(
+ globalvar.ICONDIR,
+ iconTheme,
+ 'layer-open.png')
if os.path.isfile(bitmapPath) and os.path.getsize(bitmapPath):
bitmap = wx.Bitmap(name=bitmapPath)
else:
- bitmap = wx.ArtProvider.GetBitmap(id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
+ bitmap = wx.ArtProvider.GetBitmap(
+ id=wx.ART_MISSING_IMAGE, client=wx.ART_TOOLBAR)
self.addManyMapsButton = wx.BitmapButton(self, bitmap=bitmap)
self.addManyMapsButton.Bind(wx.EVT_BUTTON, self._onAddMaps)
@@ -1330,11 +1684,16 @@
typeSizer.Add(self.tchoice)
bodySizer.Add(typeSizer, flag=wx.EXPAND | wx.BOTTOM, border=5)
- selectSizer.Add(self.tselect, flag=wx.RIGHT | wx.ALIGN_CENTER_VERTICAL, border=5)
+ selectSizer.Add(self.tselect, flag=wx.RIGHT |
+ wx.ALIGN_CENTER_VERTICAL, border=5)
selectSizer.Add(self.addManyMapsButton, flag=wx.EXPAND)
bodySizer.Add(selectSizer, flag=wx.BOTTOM, border=5)
bodySizer.Add(self.editBtn, flag=wx.BOTTOM, border=5)
- mainSizer.Add(bodySizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=10)
+ mainSizer.Add(
+ bodySizer,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=10)
btnSizer = wx.StdDialogButtonSizer()
btnSizer.AddButton(self.okBtn)
@@ -1401,8 +1760,9 @@
def _onAddMaps(self, event):
dlg = MapLayersDialog(self, title=_("Select raster/vector maps."))
- dlg.applyAddingMapLayers.connect(lambda mapLayers:
- self.tselect.SetValue(','.join(mapLayers)))
+ dlg.applyAddingMapLayers.connect(
+ lambda mapLayers: self.tselect.SetValue(
+ ','.join(mapLayers)))
if self._mapType == 'raster':
index = 0
elif self._mapType == 'vector':
@@ -1422,12 +1782,13 @@
def _onProperties(self, event):
self._checkInput()
if self._cmd:
- GUI(parent=self, show=True, modal=True).ParseCommand(cmd=self._cmd,
- completed=(self._getOptData, '', ''))
+ GUI(parent=self, show=True, modal=True).ParseCommand(
+ cmd=self._cmd, completed=(self._getOptData, '', ''))
def _checkInput(self):
if not self.tselect.GetValue():
- GMessage(parent=self, message=_("Please select maps or dataset first."))
+ GMessage(parent=self, message=_(
+ "Please select maps or dataset first."))
return
if not self._cmd:
@@ -1455,15 +1816,18 @@
class PreferencesDialog(PreferencesBaseDialog):
"""Animation preferences dialog"""
+
def __init__(self, parent, giface, title=_("Animation Tool settings"),
settings=UserSettings):
- PreferencesBaseDialog.__init__(self, parent=parent, giface=giface, title=title,
- settings=settings, size=(-1, 270))
+ PreferencesBaseDialog.__init__(
+ self, parent=parent, giface=giface, title=title, settings=settings,
+ size=(-1, 270))
self.formatChanged = Signal('PreferencesDialog.formatChanged')
self._timeFormats = ['%Y-%m-%d %H:%M:%S', # 2013-12-29 11:16:26
'%Y-%m-%d', # 2013-12-29
- '%c', # Sun Dec 29 11:16:26 2013 (locale-dependent)
+ '%c',
+ # Sun Dec 29 11:16:26 2013 (locale-dependent)
'%x', # 12/29/13 (locale-dependent)
'%X', # 11:16:26 (locale-dependent)
'%b %d, %Y', # Dec 29, 2013
@@ -1493,60 +1857,103 @@
gridSizer = wx.GridBagSizer(hgap=3, vgap=3)
row = 0
- gridSizer.Add(item=wx.StaticText(parent=panel,
- label=_("Background color:")),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- color = csel.ColourSelect(parent=panel,
- colour=UserSettings.Get(group='animation',
- key='bgcolor', subkey='color'),
- size=globalvar.DIALOG_COLOR_SIZE)
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ label=_("Background color:")),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
+ color = csel.ColourSelect(
+ parent=panel,
+ colour=UserSettings.Get(
+ group='animation',
+ key='bgcolor',
+ subkey='color'),
+ size=globalvar.DIALOG_COLOR_SIZE)
color.SetName('GetColour')
self.winId['animation:bgcolor:color'] = color.GetId()
gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
row += 1
- gridSizer.Add(item=wx.StaticText(parent=panel,
- label=_("Number of parallel processes:")),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- # when running for the first time, set nprocs based on the number of processes
- if UserSettings.Get(group='animation', key='nprocs', subkey='value') == -1:
- UserSettings.Set(group='animation', key='nprocs', subkey='value', value=getCpuCount())
- nprocs = wx.SpinCtrl(parent=panel,
- initial=UserSettings.Get(group='animation', key='nprocs', subkey='value'))
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ label=_("Number of parallel processes:")),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
+ # when running for the first time, set nprocs based on the number of
+ # processes
+ if UserSettings.Get(group='animation', key='nprocs',
+ subkey='value') == -1:
+ UserSettings.Set(
+ group='animation',
+ key='nprocs',
+ subkey='value',
+ value=getCpuCount())
+ nprocs = wx.SpinCtrl(
+ parent=panel,
+ initial=UserSettings.Get(
+ group='animation',
+ key='nprocs',
+ subkey='value'))
nprocs.SetName('GetValue')
self.winId['animation:nprocs:value'] = nprocs.GetId()
gridSizer.Add(item=nprocs, pos=(row, 1), flag=wx.ALIGN_RIGHT)
row += 1
- gridSizer.Add(item=wx.StaticText(parent=panel,
- label=_("Text foreground color:")),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- color = csel.ColourSelect(parent=panel,
- colour=UserSettings.Get(group='animation',
- key='font', subkey='fgcolor'),
- size=globalvar.DIALOG_COLOR_SIZE)
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ label=_("Text foreground color:")),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
+ color = csel.ColourSelect(
+ parent=panel,
+ colour=UserSettings.Get(
+ group='animation',
+ key='font',
+ subkey='fgcolor'),
+ size=globalvar.DIALOG_COLOR_SIZE)
color.SetName('GetColour')
self.winId['animation:font:fgcolor'] = color.GetId()
gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
row += 1
- gridSizer.Add(item=wx.StaticText(parent=panel,
- label=_("Text background color:")),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- color = csel.ColourSelect(parent=panel,
- colour=UserSettings.Get(group='animation',
- key='font', subkey='bgcolor'),
- size=globalvar.DIALOG_COLOR_SIZE)
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ label=_("Text background color:")),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
+ color = csel.ColourSelect(
+ parent=panel,
+ colour=UserSettings.Get(
+ group='animation',
+ key='font',
+ subkey='bgcolor'),
+ size=globalvar.DIALOG_COLOR_SIZE)
color.SetName('GetColour')
self.winId['animation:font:bgcolor'] = color.GetId()
gridSizer.Add(item=color, pos=(row, 1), flag=wx.ALIGN_RIGHT)
gridSizer.AddGrowableCol(1)
- sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+ sizer.Add(
+ item=gridSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=3)
border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
panel.SetSizer(border)
@@ -1563,47 +1970,77 @@
gridSizer = wx.GridBagSizer(hgap=5, vgap=5)
row = 0
- gridSizer.Add(item=wx.StaticText(parent=panel,
- label=_("Absolute time format:")),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ label=_("Absolute time format:")),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
self.tempFormat = wx.ComboBox(parent=panel, name='GetValue')
self.tempFormat.SetItems(self._timeFormats)
self.tempFormat.SetValue(self._initFormat)
self.winId['animation:temporal:format'] = self.tempFormat.GetId()
gridSizer.Add(item=self.tempFormat, pos=(row, 1), flag=wx.ALIGN_RIGHT)
self.infoTimeLabel = wx.StaticText(parent=panel)
- self.tempFormat.Bind(wx.EVT_COMBOBOX, lambda evt: self._setTimeFormat(self.tempFormat.GetValue()))
- self.tempFormat.Bind(wx.EVT_TEXT, lambda evt: self._setTimeFormat(self.tempFormat.GetValue()))
- self.tempFormat.SetToolTipString(_("Click and then press key up or down to preview "
- "different date and time formats. "
- "Type custom format string."))
+ self.tempFormat.Bind(
+ wx.EVT_COMBOBOX,
+ lambda evt: self._setTimeFormat(
+ self.tempFormat.GetValue()))
+ self.tempFormat.Bind(
+ wx.EVT_TEXT, lambda evt: self._setTimeFormat(
+ self.tempFormat.GetValue()))
+ self.tempFormat.SetToolTipString(
+ _(
+ "Click and then press key up or down to preview "
+ "different date and time formats. "
+ "Type custom format string."))
row += 1
gridSizer.Add(item=self.infoTimeLabel, pos=(row, 0), span=(1, 2),
flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
self._setTimeFormat(self.tempFormat.GetValue())
row += 1
- link = wx.HyperlinkCtrl(panel, id=wx.ID_ANY, label=_("Learn more about formatting options"),
- url="http://docs.python.org/2/library/datetime.html#"
- "strftime-and-strptime-behavior")
- link.SetNormalColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
- link.SetVisitedColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_GRAYTEXT))
+ link = wx.HyperlinkCtrl(
+ panel, id=wx.ID_ANY,
+ label=_("Learn more about formatting options"),
+ url="http://docs.python.org/2/library/datetime.html#"
+ "strftime-and-strptime-behavior")
+ link.SetNormalColour(
+ wx.SystemSettings_GetColour(
+ wx.SYS_COLOUR_GRAYTEXT))
+ link.SetVisitedColour(
+ wx.SystemSettings_GetColour(
+ wx.SYS_COLOUR_GRAYTEXT))
gridSizer.Add(item=link, pos=(row, 0), span=(1, 2),
flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
row += 2
- noDataCheck = wx.CheckBox(panel, label=_("Display instances with no data"))
- noDataCheck.SetToolTipString(_("When animating instant-based data which have irregular timestamps "
- "you can display 'no data frame' (checked option) or "
- "keep last frame."))
- noDataCheck.SetValue(self.settings.Get(group='animation', key='temporal',
- subkey=['nodata', 'enable']))
+ noDataCheck = wx.CheckBox(
+ panel, label=_("Display instances with no data"))
+ noDataCheck.SetToolTipString(
+ _(
+ "When animating instant-based data which have irregular timestamps "
+ "you can display 'no data frame' (checked option) or "
+ "keep last frame."))
+ noDataCheck.SetValue(
+ self.settings.Get(
+ group='animation',
+ key='temporal',
+ subkey=[
+ 'nodata',
+ 'enable']))
self.winId['animation:temporal:nodata:enable'] = noDataCheck.GetId()
gridSizer.Add(item=noDataCheck, pos=(row, 0), span=(1, 2),
flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
gridSizer.AddGrowableCol(1)
- sizer.Add(item=gridSizer, proportion=1, flag=wx.ALL | wx.EXPAND, border=3)
+ sizer.Add(
+ item=gridSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=3)
border.Add(item=sizer, proportion=0, flag=wx.ALL | wx.EXPAND, border=3)
panel.SetSizer(border)
Modified: grass/trunk/gui/wxpython/animation/frame.py
===================================================================
--- grass/trunk/gui/wxpython/animation/frame.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/frame.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -47,6 +47,7 @@
class AnimationFrame(wx.Frame):
+
def __init__(self, parent, giface, title=_("GRASS GIS Animation tool"),
rasters=None, timeseries=None):
wx.Frame.__init__(self, parent, title=title,
@@ -55,26 +56,35 @@
self.SetClientSize(self.GetSize())
self.iconsize = (16, 16)
- self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_map.ico'), wx.BITMAP_TYPE_ICO))
+ self.SetIcon(
+ wx.Icon(
+ os.path.join(
+ globalvar.ICONDIR,
+ 'grass_map.ico'),
+ wx.BITMAP_TYPE_ICO))
# Make sure the temporal database exists
tgis.init()
- # create temporal directory and ensure it's deleted after programs ends (stored in MAPSET/.tmp/)
+ # create temporal directory and ensure it's deleted after programs ends
+ # (stored in MAPSET/.tmp/)
global TMP_DIR
TMP_DIR = gcore.tempdir()
self.animations = [Animation() for i in range(MAX_COUNT)]
self.windows = []
- self.animationPanel = AnimationsPanel(self, self.windows, initialCount=MAX_COUNT)
+ self.animationPanel = AnimationsPanel(
+ self, self.windows, initialCount=MAX_COUNT)
bitmapPool = BitmapPool()
mapFilesPool = MapFilesPool()
self._progressDlg = None
self._progressDlgMax = None
- self.provider = BitmapProvider(bitmapPool=bitmapPool,
- mapFilesPool=mapFilesPool, tempDir=TMP_DIR)
+ self.provider = BitmapProvider(
+ bitmapPool=bitmapPool,
+ mapFilesPool=mapFilesPool,
+ tempDir=TMP_DIR)
self.animationSliders = {}
self.animationSliders['nontemporal'] = SimpleAnimationSlider(self)
self.animationSliders['temporal'] = TimeAnimationSlider(self)
@@ -91,7 +101,8 @@
self.provider.renderingStarted.connect(self._showRenderingProgress)
self.provider.renderingContinues.connect(self._updateProgress)
self.provider.renderingFinished.connect(self._closeProgress)
- self.provider.compositionStarted.connect(self._showRenderingProgress)
+ self.provider.compositionStarted.connect(
+ self._showRenderingProgress)
self.provider.compositionContinues.connect(self._updateProgress)
self.provider.compositionFinished.connect(self._closeProgress)
@@ -126,9 +137,12 @@
Floatable(False).BestSize((-1, -1)).
CloseButton(False).DestroyOnClose(True).Layer(0))
for name, slider in self.animationSliders.iteritems():
- self._mgr.AddPane(slider, wx.aui.AuiPaneInfo().PaneBorder(False).Name('slider_' + name).
- Layer(1).CaptionVisible(False).BestSize(slider.GetBestSize()).
- DestroyOnClose(True).CloseButton(False).Bottom())
+ self._mgr.AddPane(
+ slider,
+ wx.aui.AuiPaneInfo().PaneBorder(False).Name(
+ 'slider_' +
+ name). Layer(1).CaptionVisible(False).BestSize(
+ slider.GetBestSize()). DestroyOnClose(True).CloseButton(False).Bottom())
self._mgr.GetPane('slider_' + name).Hide()
def _addToolbar(self, name):
@@ -159,7 +173,8 @@
BottomDockable(True).TopDockable(True).
CloseButton(False).Layer(2).Row(1).
BestSize((self.toolbars['animationToolbar'].GetBestSize())))
- self.controller.SetAnimationToolbar(self.toolbars['animationToolbar'])
+ self.controller.SetAnimationToolbar(
+ self.toolbars['animationToolbar'])
elif name == 'miscToolbar':
self.toolbars[name] = MiscToolbar(self)
self._mgr.AddPane(self.toolbars[name],
@@ -245,9 +260,10 @@
else:
win.Show()
else: # start
- win = SpeedDialog(self, temporalMode=self.controller.GetTemporalMode(),
- timeGranularity=self.controller.GetTimeGranularity(),
- initialSpeed=self.controller.timeTick)
+ win = SpeedDialog(
+ self, temporalMode=self.controller.GetTemporalMode(),
+ timeGranularity=self.controller.GetTimeGranularity(),
+ initialSpeed=self.controller.timeTick)
win.CenterOnParent()
self.dialogs['speed'] = win
win.speedChanged.connect(self.ChangeSpeed)
@@ -260,13 +276,14 @@
self.controller.Reload()
def _showRenderingProgress(self, count):
- # the message is not really visible, it's there for the initial dlg size
- self._progressDlg = wx.ProgressDialog(title=_("Loading data"),
- message="Loading data started, please be patient.",
- maximum=count,
- parent=self,
- style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
- wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
+ # the message is not really visible, it's there for the initial dlg
+ # size
+ self._progressDlg = wx.ProgressDialog(
+ title=_("Loading data"),
+ message="Loading data started, please be patient.",
+ maximum=count,
+ parent=self,
+ style=wx.PD_CAN_ABORT | wx.PD_APP_MODAL | wx.PD_AUTO_HIDE | wx.PD_SMOOTH)
self._progressDlgMax = count
def _updateProgress(self, current, text):
@@ -296,7 +313,8 @@
if not self.dialogs['preferences']:
dlg = PreferencesDialog(parent=self, giface=self._giface)
self.dialogs['preferences'] = dlg
- dlg.formatChanged.connect(lambda: self.controller.UpdateAnimations())
+ dlg.formatChanged.connect(
+ lambda: self.controller.UpdateAnimations())
dlg.CenterOnParent()
self.dialogs['preferences'].ShowModal()
@@ -308,7 +326,7 @@
def OnCloseWindow(self, event):
if self.controller.timer.IsRunning():
- self.controller.timer.Stop()
+ self.controller.timer.Stop()
CleanUp(TMP_DIR)()
self.Destroy()
@@ -321,6 +339,7 @@
class AnimationsPanel(wx.Panel):
+
def __init__(self, parent, windows, initialCount=4):
wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.NO_BORDER)
self.shown = []
@@ -361,6 +380,7 @@
class AnimationSliderBase(wx.Panel):
+
def __init__(self, parent):
wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
self.label1 = wx.StaticText(self, id=wx.ID_ANY)
@@ -449,6 +469,7 @@
class SimpleAnimationSlider(AnimationSliderBase):
+
def __init__(self, parent):
AnimationSliderBase.__init__(self, parent)
@@ -461,7 +482,11 @@
flag=wx.ALIGN_CENTER | wx.LEFT, border=5)
hbox.Add(item=self.label1, proportion=0,
flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT, border=5)
- hbox.Add(item=self.slider, proportion=1, flag=wx.ALIGN_CENTER | wx.EXPAND, border=0)
+ hbox.Add(
+ item=self.slider,
+ proportion=1,
+ flag=wx.ALIGN_CENTER | wx.EXPAND,
+ border=0)
self.SetSizerAndFit(hbox)
def _setFrames(self, count):
@@ -483,6 +508,7 @@
class TimeAnimationSlider(AnimationSliderBase):
+
def __init__(self, parent):
AnimationSliderBase.__init__(self, parent)
self.timeLabels = []
@@ -510,7 +536,11 @@
vbox.Add(item=hbox, proportion=0, flag=wx.EXPAND, border=0)
hbox = wx.BoxSizer(wx.HORIZONTAL)
- hbox.Add(item=self.slider, proportion=1, flag=wx.ALIGN_CENTER | wx.EXPAND, border=0)
+ hbox.Add(
+ item=self.slider,
+ proportion=1,
+ flag=wx.ALIGN_CENTER | wx.EXPAND,
+ border=0)
vbox.Add(item=hbox, proportion=0, flag=wx.EXPAND, border=0)
self._setTemporalType()
@@ -572,8 +602,10 @@
start = self.timeLabels[index][0]
if self.timeLabels[index][1]: # interval
if self.temporalType == TemporalType.ABSOLUTE:
- label = _("%(from)s %(dash)s %(to)s") % \
- {'from': start, 'dash': u"\u2013", 'to': self.timeLabels[index][1]}
+ label = _("%(from)s %(dash)s %(to)s") % {
+ 'from': start,
+ 'dash': u"\u2013",
+ 'to': self.timeLabels[index][1]}
else:
label = _("to %(to)s") % {'to': self.timeLabels[index][1]}
else:
Modified: grass/trunk/gui/wxpython/animation/g.gui.animation.py
===================================================================
--- grass/trunk/gui/wxpython/animation/g.gui.animation.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/g.gui.animation.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -64,7 +64,7 @@
from grass.script.setup import set_gui_path
set_gui_path()
-
+
from core.globalvar import CheckWxVersion
from core.utils import _
from core.giface import StandaloneGrassInterface
@@ -133,7 +133,8 @@
frame.Show()
if len(layerList) >= 1:
# CallAfter added since it was crashing with wxPython 3 gtk
- wx.CallAfter(frame.SetAnimations, [layerList] + [None] * (MAX_COUNT - 1))
+ wx.CallAfter(frame.SetAnimations,
+ [layerList] + [None] * (MAX_COUNT - 1))
app.MainLoop()
if __name__ == '__main__':
Modified: grass/trunk/gui/wxpython/animation/mapwindow.py
===================================================================
--- grass/trunk/gui/wxpython/animation/mapwindow.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/mapwindow.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,10 +35,11 @@
SaveToFile(self, file_name, file_type) method.
"""
+
def __init__(self, *args, **kwargs):
# make sure the NO_FULL_REPAINT_ON_RESIZE style flag is set.
- kwargs['style'] = kwargs.setdefault('style', wx.NO_FULL_REPAINT_ON_RESIZE) | \
- wx.NO_FULL_REPAINT_ON_RESIZE
+ kwargs['style'] = kwargs.setdefault(
+ 'style', wx.NO_FULL_REPAINT_ON_RESIZE) | wx.NO_FULL_REPAINT_ON_RESIZE
wx.Window.__init__(self, *args, **kwargs)
Debug.msg(2, "BufferedWindow.__init__()")
@@ -50,8 +51,8 @@
self.OnSize(None)
def Draw(self, dc):
- ## just here as a place holder.
- ## This method should be over-ridden when subclassed
+ # just here as a place holder.
+ # This method should be over-ridden when subclassed
pass
def OnPaint(self, event):
@@ -74,9 +75,9 @@
# event.Skip()
def SaveToFile(self, FileName, FileType=wx.BITMAP_TYPE_PNG):
- ## This will save the contents of the buffer
- ## to the specified file. See the wxWindows docs for
- ## wx.Bitmap::SaveFile for the details
+ # This will save the contents of the buffer
+ # to the specified file. See the wxWindows docs for
+ # wx.Bitmap::SaveFile for the details
self._Buffer.SaveFile(FileName, FileType)
def UpdateDrawing(self):
@@ -98,6 +99,7 @@
class AnimationWindow(BufferedWindow):
+
def __init__(self, parent, id=wx.ID_ANY,
style=wx.DEFAULT_FRAME_STYLE | wx.FULL_REPAINT_ON_RESIZE |
wx.BORDER_RAISED):
@@ -145,8 +147,15 @@
bitmap = wx.BitmapFromImage(im)
if self._overlay:
im = wx.ImageFromBitmap(self.bitmap_overlay)
- im.Rescale(im.GetWidth() * params['scale'], im.GetHeight() * params['scale'])
- self._setOverlay(wx.BitmapFromImage(im), xperc=self.perc[0], yperc=self.perc[1])
+ im.Rescale(
+ im.GetWidth() *
+ params['scale'],
+ im.GetHeight() *
+ params['scale'])
+ self._setOverlay(
+ wx.BitmapFromImage(im),
+ xperc=self.perc[0],
+ yperc=self.perc[1])
else:
self.x = 0
self.y = 0
Modified: grass/trunk/gui/wxpython/animation/nviztask.py
===================================================================
--- grass/trunk/gui/wxpython/animation/nviztask.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/nviztask.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -28,6 +28,7 @@
class NvizTask:
+
def __init__(self):
self.task = None
self.filename = None
@@ -48,7 +49,9 @@
# pprint(gxwXml.nviz_state)
if not gxwXml.nviz_state:
- raise GException(_("No 3d view information in workspace file <%s>.") % self.filename)
+ raise GException(
+ _("No 3d view information in workspace file <%s>.") %
+ self.filename)
self._getExtent(gxwXml)
self._processState(gxwXml.nviz_state)
@@ -58,8 +61,8 @@
for display in root.displays:
if display['viewMode'] == '3d':
self.region['w'], self.region['s'],\
- self.region['e'], self.region['n'],\
- self.region['b'], self.region['t'] = display['extent']
+ self.region['e'], self.region['n'],\
+ self.region['b'], self.region['t'] = display['extent']
self.region['tbres'] = display['tbres']
def _processLayers(self, layers):
@@ -69,18 +72,22 @@
if not layer['nviz']:
continue
- layerName, found = GetLayerNameFromCmd(layer['cmd'], fullyQualified=False,
- param='map')
+ layerName, found = GetLayerNameFromCmd(
+ layer['cmd'], fullyQualified=False, param='map')
if not found:
continue
if 'surface' in layer['nviz']:
- self._processSurface(layer['nviz']['surface'], mapName=layerName)
+ self._processSurface(
+ layer['nviz']['surface'],
+ mapName=layerName)
if 'volume' in layer['nviz']:
self._processVolume(layer['nviz']['volume'], mapName=layerName)
if 'vector' in layer['nviz']:
if 'points' in layer['nviz']['vector']:
- self._processPoints(layer['nviz']['vector']['points'], mapName=layerName)
+ self._processPoints(
+ layer['nviz']['vector']['points'],
+ mapName=layerName)
def _processSurface(self, surface, mapName):
self._setMultiTaskParam('elevation_map', mapName)
@@ -88,8 +95,8 @@
# attributes like color, shine, transparency
attributes = ('color', 'shine', 'transp') # mask missing
parameters = (('color_map', 'color'),
- ('shininess_map', 'shininess_value'),
- ('transparency_map', 'transparency_value'))
+ ('shininess_map', 'shininess_value'),
+ ('transparency_map', 'transparency_value'))
for attr, params in zip(attributes, parameters):
mapname = None
const = None
@@ -117,7 +124,9 @@
value = surface['draw']['wire-color']['value']
self._setMultiTaskParam('wire_color', value)
# resolution
- for mode1, mode2 in zip(('coarse', 'fine'), ('resolution_coarse', 'resolution_fine')):
+ for mode1, mode2 in zip(
+ ('coarse', 'fine'),
+ ('resolution_coarse', 'resolution_fine')):
value = surface['draw']['resolution'][mode1]
self._setMultiTaskParam(mode2, value)
@@ -135,11 +144,16 @@
self._setMultiTaskParam('vpoint_' + attrib, str(val))
if 'height' in points:
height = points['height']['value']
- self._setMultiTaskParam('vpoint_position', '0,0,{h}'.format(h=height))
+ self._setMultiTaskParam(
+ 'vpoint_position',
+ '0,0,{h}'.format(
+ h=height))
if 'marker' in points:
- marker = list(UserSettings.Get(group='nviz', key='vector',
- subkey=['points', 'marker'],
- settings_type='internal'))[points['marker']['value']]
+ marker = list(
+ UserSettings.Get(
+ group='nviz', key='vector', subkey=[
+ 'points', 'marker'], settings_type='internal'))[
+ points['marker']['value']]
self._setMultiTaskParam('vpoint_marker', marker)
if 'mode' in points:
if points['mode']['type'] == '3d':
@@ -160,10 +174,11 @@
self._setMultiTaskParam('volume_resolution', res_value)
for isosurface in isosurfaces:
attributes = ('topo', 'color', 'shine', 'transp')
- parameters = ((None, 'isosurf_level'),
- ('isosurf_color_map', 'isosurf_color_value'),
- ('isosurf_shininess_map', 'isosurf_shininess_value'),
- ('isosurf_transparency_map', 'isosurf_transparency_value'))
+ parameters = (
+ (None, 'isosurf_level'),
+ ('isosurf_color_map', 'isosurf_color_value'),
+ ('isosurf_shininess_map', 'isosurf_shininess_value'),
+ ('isosurf_transparency_map', 'isosurf_transparency_value'))
for attr, params in zip(attributes, parameters):
mapname = None
const = None
@@ -182,8 +197,10 @@
self._setMultiTaskParam(params[0], mapname)
else:
if attr == 'topo':
- # TODO: we just assume it's the first volume, what to do else?
- self._setMultiTaskParam(params[1], '1:' + str(const))
+ # TODO: we just assume it's the first volume, what
+ # to do else?
+ self._setMultiTaskParam(
+ params[1], '1:' + str(const))
else:
self._setMultiTaskParam(params[1], const)
if isosurface['inout']['value']:
@@ -194,12 +211,15 @@
res_value = volume['draw']['resolution']['slice']['value']
self._setMultiTaskParam('volume_resolution', res_value)
for slice_ in slices:
- self._setMultiTaskParam('slice_transparency', slice_['transp']['value'])
+ self._setMultiTaskParam(
+ 'slice_transparency', slice_['transp']['value'])
axis = slice_['position']['axis']
self._setMultiTaskParam('slice', '1:' + 'xyz'[axis])
pos = slice_['position']
- coords = pos['x1'], pos['x2'], pos['y1'], pos['y2'], pos['z1'], pos['z2']
- self._setMultiTaskParam('slice_position', ','.join([str(c) for c in coords]))
+ coords = pos['x1'], pos['x2'], pos[
+ 'y1'], pos['y2'], pos['z1'], pos['z2']
+ self._setMultiTaskParam('slice_position', ','.join(
+ [str(c) for c in coords]))
# position
pos = []
@@ -212,19 +232,25 @@
def _processState(self, state):
color = state['view']['background']['color']
self.task.set_param('bgcolor', self._join(color, delim=':'))
- self.task.set_param('position', self._join((state['view']['position']['x'],
- state['view']['position']['y'])))
+ self.task.set_param(
+ 'position', self._join(
+ (state['view']['position']['x'],
+ state['view']['position']['y'])))
self.task.set_param('height', state['iview']['height']['value'])
self.task.set_param('perspective', state['view']['persp']['value'])
self.task.set_param('twist', state['view']['twist']['value'])
# TODO: fix zexag
self.task.set_param('zexag', state['view']['z-exag']['value'])
- self.task.set_param('focus', self._join((state['iview']['focus']['x'],
- state['iview']['focus']['y'],
- state['iview']['focus']['z'])))
- self.task.set_param('light_position', self._join((state['light']['position']['x'],
- state['light']['position']['y'],
- state['light']['position']['z'] / 100.)))
+ self.task.set_param(
+ 'focus', self._join(
+ (state['iview']['focus']['x'],
+ state['iview']['focus']['y'],
+ state['iview']['focus']['z'])))
+ self.task.set_param(
+ 'light_position', self._join(
+ (state['light']['position']['x'],
+ state['light']['position']['y'],
+ state['light']['position']['z'] / 100.)))
color = state['light']['color'][:3]
self.task.set_param('light_color', self._join(color, delim=':'))
self.task.set_param('light_brightness', int(state['light']['bright']))
@@ -262,7 +288,8 @@
if hasattr(layer, 'maps'):
series = layer.maps
else:
- raise GException(_("No map series nor space-time dataset is added."))
+ raise GException(
+ _("No map series nor space-time dataset is added."))
for value in series:
self.task.set_param(paramName, value)
@@ -273,7 +300,10 @@
self.task.set_param('isosurf_color_map', '')
self.task.set_flag('overwrite', True)
self.task.set_param('output', 'tobechanged')
- cmd = self.task.get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True)
+ cmd = self.task.get_cmd(
+ ignoreErrors=False,
+ ignoreRequired=False,
+ ignoreDefault=True)
commands.append(cmd)
return commands
@@ -283,7 +313,10 @@
return None
self.task.set_flag('overwrite', True)
self.task.set_param('output', 'tobechanged')
- cmd = self.task.get_cmd(ignoreErrors=False, ignoreRequired=False, ignoreDefault=True)
+ cmd = self.task.get_cmd(
+ ignoreErrors=False,
+ ignoreRequired=False,
+ ignoreDefault=True)
return gtask.cmdlist_to_tuple(cmd)
def GetRegion(self):
@@ -298,7 +331,8 @@
cmds = nviz.GetCommandSeries(['aspect', 'elevation'], 'color_map')
for cmd in cmds:
print cmd
- returncode, message = RunCommand(getErrorMsg=True, prog=cmd[0], **cmd[1])
+ returncode, message = RunCommand(
+ getErrorMsg=True, prog=cmd[0], **cmd[1])
print returncode, message
Modified: grass/trunk/gui/wxpython/animation/provider.py
===================================================================
--- grass/trunk/gui/wxpython/animation/provider.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/provider.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -44,13 +44,15 @@
There is one instance of this class in the application.
It handles both 2D and 3D animations.
"""
+
def __init__(self, bitmapPool, mapFilesPool, tempDir,
imageWidth=640, imageHeight=480):
self._bitmapPool = bitmapPool
self._mapFilesPool = mapFilesPool
self.imageWidth = imageWidth # width of the image to render with d.rast or d.vect
- self.imageHeight = imageHeight # height of the image to render with d.rast or d.vect
+ # height of the image to render with d.rast or d.vect
+ self.imageHeight = imageHeight
self._tempDir = tempDir
self._uniqueCmds = []
@@ -70,7 +72,8 @@
self.renderingStarted = Signal('BitmapProvider.renderingStarted')
self.compositionStarted = Signal('BitmapProvider.compositionStarted')
self.renderingContinues = Signal('BitmapProvider.renderingContinues')
- self.compositionContinues = Signal('BitmapProvider.compositionContinues')
+ self.compositionContinues = Signal(
+ 'BitmapProvider.compositionContinues')
self.renderingFinished = Signal('BitmapProvider.renderingFinished')
self.compositionFinished = Signal('BitmapProvider.compositionFinished')
self.mapsLoaded = Signal('BitmapProvider.mapsLoaded')
@@ -89,7 +92,9 @@
:param opacities: list of opacity values
:param regions: list of regions
"""
- Debug.msg(2, "BitmapProvider.SetCmds: {n} lists".format(n=len(cmdsForComposition)))
+ Debug.msg(
+ 2, "BitmapProvider.SetCmds: {n} lists".format(
+ n=len(cmdsForComposition)))
self._cmdsForComposition.extend(cmdsForComposition)
self._opacities.extend(opacities)
self._regions.extend(regions)
@@ -102,7 +107,9 @@
:param cmds: list of commands m.nviz.image (cmd as a list)
:param region: for 3D rendering
"""
- Debug.msg(2, "BitmapProvider.SetCmds3D: {c} commands".format(c=len(cmds)))
+ Debug.msg(
+ 2, "BitmapProvider.SetCmds3D: {c} commands".format(
+ c=len(cmds)))
self._cmds3D = cmds
self._regionFor3D = region
@@ -118,8 +125,8 @@
unique.append((tuple(cmd), None))
unique = list(set(unique))
self._uniqueCmds = [cmdAndRegion[0] for cmdAndRegion in unique]
- self._regionsForUniqueCmds.extend([dict(cmdAndRegion[1]) if cmdAndRegion[1] else None
- for cmdAndRegion in unique])
+ self._regionsForUniqueCmds.extend([dict(cmdAndRegion[1]) if cmdAndRegion[
+ 1] else None for cmdAndRegion in unique])
def Unload(self):
"""Unloads currently loaded data.
@@ -127,10 +134,12 @@
"""
Debug.msg(2, "BitmapProvider.Unload")
if self._cmdsForComposition:
- for cmd, region in zip(self._uniqueCmds, self._regionsForUniqueCmds):
+ for cmd, region in zip(self._uniqueCmds,
+ self._regionsForUniqueCmds):
del self._mapFilesPool[HashCmd(cmd, region)]
- for cmdList, region in zip(self._cmdsForComposition, self._regions):
+ for cmdList, region in zip(
+ self._cmdsForComposition, self._regions):
del self._bitmapPool[HashCmds(cmdList, region)]
self._uniqueCmds = []
self._cmdsForComposition = []
@@ -151,12 +160,15 @@
count = 0
for cmd, region in zip(uniqueCmds, regions):
filename = GetFileFromCmd(self._tempDir, cmd, region)
- if not force and os.path.exists(filename) and \
- self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
+ if not force and os.path.exists(filename) and self._mapFilesPool.GetSize(
+ HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
continue
count += 1
- Debug.msg(3, "BitmapProvider._dryRender: {c} files to be rendered".format(c=count))
+ Debug.msg(
+ 3,
+ "BitmapProvider._dryRender: {c} files to be rendered".format(
+ c=count))
return count
@@ -170,13 +182,17 @@
"""
count = 0
for cmdList, region in zip(cmdLists, regions):
- if not force and HashCmds(cmdList, region) in self._bitmapPool and \
- self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
- self.imageHeight):
+ if not force and HashCmds(
+ cmdList, region) in self._bitmapPool and self._bitmapPool[
+ HashCmds(cmdList, region)].GetSize() == (
+ self.imageWidth, self.imageHeight):
continue
count += 1
- Debug.msg(2, "BitmapProvider._dryCompose: {c} files to be composed".format(c=count))
+ Debug.msg(
+ 2,
+ "BitmapProvider._dryCompose: {c} files to be composed".format(
+ c=count))
return count
@@ -206,19 +222,33 @@
# create no data bitmap
if None not in self._bitmapPool or force:
- self._bitmapPool[None] = createNoDataBitmap(self.imageWidth, self.imageHeight)
+ self._bitmapPool[None] = createNoDataBitmap(
+ self.imageWidth, self.imageHeight)
- ok = self._renderer.Render(cmds, regions, regionFor3D=self._regionFor3D,
- bgcolor=bgcolor, force=force, nprocs=nprocs)
+ ok = self._renderer.Render(
+ cmds,
+ regions,
+ regionFor3D=self._regionFor3D,
+ bgcolor=bgcolor,
+ force=force,
+ nprocs=nprocs)
self.renderingFinished.emit()
if not ok:
self.mapsLoaded.emit() # what to do here?
return
if self._cmdsForComposition:
- count = self._dryCompose(self._cmdsForComposition, self._regions, force=force)
+ count = self._dryCompose(
+ self._cmdsForComposition,
+ self._regions,
+ force=force)
self.compositionStarted.emit(count=count)
- self._composer.Compose(self._cmdsForComposition, self._regions, self._opacities,
- bgcolor=bgcolor, force=force, nprocs=nprocs)
+ self._composer.Compose(
+ self._cmdsForComposition,
+ self._regions,
+ self._opacities,
+ bgcolor=bgcolor,
+ force=force,
+ nprocs=nprocs)
self.compositionFinished.emit()
if self._cmds3D:
for cmd in self._cmds3D:
@@ -247,7 +277,9 @@
def WindowSizeChanged(self, width, height):
"""Sets size when size of related window changes."""
- Debug.msg(5, "BitmapProvider.WindowSizeChanged: w={w}, h={h}".format(w=width, h=height))
+ Debug.msg(
+ 5, "BitmapProvider.WindowSizeChanged: w={w}, h={h}".format(
+ w=width, h=height))
self.imageWidth, self.imageHeight = width, height
@@ -271,7 +303,8 @@
Debug.msg(1, "Render raster legend " + str(filename))
cmdTuple = cmdlist_to_tuple(cmd)
- returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
+ returncode, stdout, messages = read2_command(
+ cmdTuple[0], **cmdTuple[1])
if returncode == 0:
return wx.BitmapFromImage(autoCropImageFromFile(filename))
@@ -282,6 +315,7 @@
class BitmapRenderer:
"""Class which renderes 2D and 3D images to files."""
+
def __init__(self, mapFilesPool, tempDir,
imageWidth, imageHeight):
self._mapFilesPool = mapFilesPool
@@ -315,8 +349,8 @@
filteredCmdList = []
for cmd, region in zip(cmdList, regions):
filename = GetFileFromCmd(self._tempDir, cmd, region)
- if not force and os.path.exists(filename) and \
- self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
+ if not force and os.path.exists(filename) and self._mapFilesPool.GetSize(
+ HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
# for reference counting
self._mapFilesPool[HashCmd(cmd, region)] = filename
continue
@@ -332,13 +366,27 @@
q = Queue()
# The separate render process
if cmd[0] == 'm.nviz.image':
- p = Process(target=RenderProcess3D,
- args=(self.imageWidth, self.imageHeight, self._tempDir,
- cmd, regionFor3D, bgcolor, q))
+ p = Process(
+ target=RenderProcess3D,
+ args=(
+ self.imageWidth,
+ self.imageHeight,
+ self._tempDir,
+ cmd,
+ regionFor3D,
+ bgcolor,
+ q))
else:
- p = Process(target=RenderProcess2D,
- args=(self.imageWidth, self.imageHeight, self._tempDir,
- cmd, region, bgcolor, q))
+ p = Process(
+ target=RenderProcess2D,
+ args=(
+ self.imageWidth,
+ self.imageHeight,
+ self._tempDir,
+ cmd,
+ region,
+ bgcolor,
+ q))
p.start()
queue_list.append(q)
@@ -351,16 +399,22 @@
for i in range(len(cmd_list)):
proc_list[i].join()
filename = queue_list[i].get()
- self._mapFilesPool[HashCmd(cmd_list[i][0], cmd_list[i][1])] = filename
- self._mapFilesPool.SetSize(HashCmd(cmd_list[i][0], cmd_list[i][1]),
- (self.imageWidth, self.imageHeight))
+ self._mapFilesPool[
+ HashCmd(
+ cmd_list[i][0],
+ cmd_list[i][1])] = filename
+ self._mapFilesPool.SetSize(
+ HashCmd(cmd_list[i][0],
+ cmd_list[i][1]),
+ (self.imageWidth, self.imageHeight))
proc_count = 0
proc_list = []
queue_list = []
cmd_list = []
- self.renderingContinues.emit(current=count, text=_("Rendering map layers"))
+ self.renderingContinues.emit(
+ current=count, text=_("Rendering map layers"))
if self._stopRendering:
self._stopRendering = False
stopped = True
@@ -377,6 +431,7 @@
class BitmapComposer:
"""Class which handles the composition of image files with g.pnmcomp."""
+
def __init__(self, tempDir, mapFilesPool, bitmapPool,
imageWidth, imageHeight):
self._mapFilesPool = mapFilesPool
@@ -411,11 +466,19 @@
filteredCmdLists = []
for cmdList, region in zip(cmdLists, regions):
- if not force and HashCmds(cmdList, region) in self._bitmapPool and \
- self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
- self.imageHeight):
- # TODO: find a better way than to assign the same to increase the reference
- self._bitmapPool[HashCmds(cmdList, region)] = self._bitmapPool[HashCmds(cmdList, region)]
+ if not force and HashCmds(
+ cmdList, region) in self._bitmapPool and self._bitmapPool[
+ HashCmds(cmdList, region)].GetSize() == (
+ self.imageWidth, self.imageHeight):
+ # TODO: find a better way than to assign the same to increase
+ # the reference
+ self._bitmapPool[
+ HashCmds(
+ cmdList,
+ region)] = self._bitmapPool[
+ HashCmds(
+ cmdList,
+ region)]
continue
filteredCmdLists.append((cmdList, region))
@@ -444,19 +507,27 @@
proc_list[i].join()
filename = queue_list[i].get()
if filename is None:
- self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
- createNoDataBitmap(self.imageWidth, self.imageHeight,
- text="Failed to render")
+ self._bitmapPool[
+ HashCmds(
+ cmd_lists[i][0],
+ cmd_lists[i][1])] = createNoDataBitmap(
+ self.imageWidth,
+ self.imageHeight,
+ text="Failed to render")
else:
- self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
- wx.BitmapFromImage(wx.Image(filename))
+ self._bitmapPool[
+ HashCmds(
+ cmd_lists[i][0],
+ cmd_lists[i][1])] = wx.BitmapFromImage(
+ wx.Image(filename))
os.remove(filename)
proc_count = 0
proc_list = []
queue_list = []
cmd_lists = []
- self.compositionContinues.emit(current=count, text=_("Overlaying map layers"))
+ self.compositionContinues.emit(
+ current=count, text=_("Overlaying map layers"))
if self._stopComposing:
self._stopComposing = False
break
@@ -469,7 +540,8 @@
self._stopComposing = True
-def RenderProcess2D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
+def RenderProcess2D(imageWidth, imageHeight, tempDir,
+ cmd, region, bgcolor, fileQueue):
"""Render raster or vector files as ppm image and write the
resulting ppm filename in the provided file queue
@@ -506,7 +578,8 @@
fileQueue.put(filename)
-def RenderProcess3D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
+def RenderProcess3D(imageWidth, imageHeight, tempDir,
+ cmd, region, bgcolor, fileQueue):
"""Renders image with m.nviz.image and writes the
resulting ppm filename in the provided file queue
@@ -530,7 +603,8 @@
cmdTuple[1]['size'] = '%d,%d' % (imageWidth, imageHeight)
# set format
cmdTuple[1]['format'] = 'ppm'
- cmdTuple[1]['bgcolor'] = bgcolor = ':'.join([str(part) for part in bgcolor])
+ cmdTuple[1]['bgcolor'] = bgcolor = ':'.join(
+ [str(part) for part in bgcolor])
returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
if returncode != 0:
gcore.warning("Rendering failed:\n" + messages)
@@ -542,7 +616,8 @@
fileQueue.put(filename)
-def CompositeProcess(imageWidth, imageHeight, tempDir, cmdList, region, opacities, bgcolor, fileQueue):
+def CompositeProcess(imageWidth, imageHeight, tempDir,
+ cmdList, region, opacities, bgcolor, fileQueue):
"""Performs the composition of image ppm files and writes the
resulting ppm filename in the provided file queue
@@ -569,15 +644,11 @@
opacities = [str(op) for op in opacities]
bgcolor = ':'.join([str(part) for part in bgcolor])
- returncode, stdout, messages = read2_command('g.pnmcomp',
- overwrite=True,
- input='%s' % ",".join(reversed(maps)),
- mask='%s' % ",".join(reversed(masks)),
- opacity='%s' % ",".join(reversed(opacities)),
- bgcolor=bgcolor,
- width=imageWidth,
- height=imageHeight,
- output=filename)
+ returncode, stdout, messages = read2_command(
+ 'g.pnmcomp', overwrite=True, input='%s' % ",".join(reversed(maps)),
+ mask='%s' % ",".join(reversed(masks)),
+ opacity='%s' % ",".join(reversed(opacities)),
+ bgcolor=bgcolor, width=imageWidth, height=imageHeight, output=filename)
if returncode != 0:
gcore.warning("Rendering composite failed:\n" + messages)
@@ -592,6 +663,7 @@
"""Base class storing map files/bitmaps (emulates dictionary).
Counts the references to know which files/bitmaps to delete.
"""
+
def __init__(self):
self.dictionary = {}
self.referenceCount = {}
@@ -605,14 +677,16 @@
self.referenceCount[key] = 1
else:
self.referenceCount[key] += 1
- Debug.msg(5, 'DictRefCounter.__setitem__: +1 for key {k}'.format(k=key))
+ Debug.msg(
+ 5, 'DictRefCounter.__setitem__: +1 for key {k}'.format(k=key))
def __contains__(self, key):
return key in self.dictionary
def __delitem__(self, key):
self.referenceCount[key] -= 1
- Debug.msg(5, 'DictRefCounter.__delitem__: -1 for key {k}'.format(k=key))
+ Debug.msg(
+ 5, 'DictRefCounter.__delitem__: -1 for key {k}'.format(k=key))
def keys(self):
return self.dictionary.keys()
@@ -629,6 +703,7 @@
class MapFilesPool(DictRefCounter):
"""Stores rendered images as files."""
+
def __init__(self):
DictRefCounter.__init__(self)
self.size = {}
@@ -658,12 +733,14 @@
class BitmapPool(DictRefCounter):
"""Class storing bitmaps (emulates dictionary)"""
+
def __init__(self):
DictRefCounter.__init__(self)
class CleanUp:
"""Responsible for cleaning up the files."""
+
def __init__(self, tempDir):
self._tempDir = tempDir
@@ -672,9 +749,13 @@
if os.path.exists(self._tempDir):
try:
shutil.rmtree(self._tempDir)
- Debug.msg(5, 'CleanUp: removed directory {t}'.format(t=self._tempDir))
+ Debug.msg(
+ 5, 'CleanUp: removed directory {t}'.format(
+ t=self._tempDir))
except OSError:
- gcore.warning(_("Directory {t} not removed.").format(t=self._tempDir))
+ gcore.warning(
+ _("Directory {t} not removed.").format(
+ t=self._tempDir))
def _setEnvironment(width, height, filename, transparent, bgcolor):
@@ -686,20 +767,22 @@
:param transparent: use transparency
:param bgcolor: background color as a tuple of 3 values 0 to 255
"""
- Debug.msg(5, "_setEnvironment: width={w}, height={h}, "
- "filename={f}, transparent={t}, bgcolor={b}".format(w=width,
- h=height,
- f=filename,
- t=transparent,
- b=bgcolor))
+ Debug.msg(
+ 5,
+ "_setEnvironment: width={w}, height={h}, "
+ "filename={f}, transparent={t}, bgcolor={b}".format(
+ w=width,
+ h=height,
+ f=filename,
+ t=transparent,
+ b=bgcolor))
os.environ['GRASS_RENDER_WIDTH'] = str(width)
os.environ['GRASS_RENDER_HEIGHT'] = str(height)
driver = UserSettings.Get(group='display', key='driver', subkey='type')
os.environ['GRASS_RENDER_IMMEDIATE'] = driver
- os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = '{r:02x}{g:02x}{b:02x}'.format(r=bgcolor[0],
- g=bgcolor[1],
- b=bgcolor[2])
+ os.environ['GRASS_RENDER_BACKGROUNDCOLOR'] = '{r:02x}{g:02x}{b:02x}'.format(
+ r=bgcolor[0], g=bgcolor[1], b=bgcolor[2])
os.environ['GRASS_RENDER_TRUECOLOR'] = "TRUE"
if transparent:
os.environ['GRASS_RENDER_TRANSPARENT'] = "TRUE"
@@ -717,9 +800,8 @@
:param imageWidth: image width
:param imageHeight: image height
"""
- Debug.msg(4, "createNoDataBitmap: w={w}, h={h}, text={t}".format(w=imageWidth,
- h=imageHeight,
- t=text))
+ Debug.msg(4, "createNoDataBitmap: w={w}, h={h}, text={t}".format(
+ w=imageWidth, h=imageHeight, t=text))
bitmap = wx.EmptyBitmap(imageWidth, imageHeight)
dc = wx.MemoryDC()
dc.SelectObject(bitmap)
@@ -780,13 +862,19 @@
prov = BitmapProvider(bPool, mapFilesPool, tempDir,
imageWidth=640, imageHeight=480)
prov.renderingStarted.connect(
- lambda count: sys.stdout.write("Total number of maps: {c}\n".format(c=count)))
+ lambda count: sys.stdout.write(
+ "Total number of maps: {c}\n".format(
+ c=count)))
prov.renderingContinues.connect(
- lambda current, text: sys.stdout.write("Current number: {c}\n".format(c=current)))
- prov.compositionStarted.connect(
- lambda count: sys.stdout.write("Composition: total number of maps: {c}\n".format(c=count)))
+ lambda current, text: sys.stdout.write(
+ "Current number: {c}\n".format(
+ c=current)))
+ prov.compositionStarted.connect(lambda count: sys.stdout.write(
+ "Composition: total number of maps: {c}\n".format(c=count)))
prov.compositionContinues.connect(
- lambda current, text: sys.stdout.write("Composition: Current number: {c}\n".format(c=current)))
+ lambda current, text: sys.stdout.write(
+ "Composition: Current number: {c}\n".format(
+ c=current)))
prov.mapsLoaded.connect(
lambda: sys.stdout.write("Maps loading finished\n"))
cmdMatrix = layerListToCmdsMatrix(layerList)
@@ -797,7 +885,11 @@
for key in bPool.keys():
if key is not None:
- bPool[key].SaveFile(os.path.join(tempDir, key + '.png'), wx.BITMAP_TYPE_PNG)
+ bPool[key].SaveFile(
+ os.path.join(
+ tempDir,
+ key + '.png'),
+ wx.BITMAP_TYPE_PNG)
# prov.Unload()
# prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
# prov.Load(bgcolor=(13, 156, 230))
Modified: grass/trunk/gui/wxpython/animation/temporal_manager.py
===================================================================
--- grass/trunk/gui/wxpython/animation/temporal_manager.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/temporal_manager.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,6 +40,7 @@
class TemporalManager(object):
"""Class for temporal data processing."""
+
def __init__(self):
self.timeseriesList = []
self.timeseriesInfo = {}
@@ -69,7 +70,11 @@
:param timeseries: name of timeseries (with or without mapset)
:param etype: element type (strds, stvds)
"""
- self._gatherInformation(timeseries, etype, self.timeseriesList, self.timeseriesInfo)
+ self._gatherInformation(
+ timeseries,
+ etype,
+ self.timeseriesList,
+ self.timeseriesInfo)
def EvaluateInputData(self):
"""Checks if all timeseries are compatible (raises GException).
@@ -116,7 +121,8 @@
for infoDict in self.timeseriesInfo.values():
units.add(infoDict['unit'])
if len(units) > 1:
- message = _("It is not allowed to display data with different units (%s).") % ','.join(units)
+ message = _(
+ "It is not allowed to display data with different units (%s).") % ','.join(units)
return False, message
# check for interval x point
@@ -127,9 +133,10 @@
else:
point += 1
if bool(interval) == bool(point):
- message = _("You are going to display data with different "
- "temporal types of maps (interval and point)."
- " It is recommended to use data of one temporal type to avoid confusion.")
+ message = _(
+ "You are going to display data with different "
+ "temporal types of maps (interval and point)."
+ " It is recommended to use data of one temporal type to avoid confusion.")
return True, message # warning
return True, None
@@ -139,7 +146,8 @@
"""
if self.dataMode == DataMode.SIMPLE:
gran = self.timeseriesInfo[self.timeseriesList[0]]['granularity']
- if 'unit' in self.timeseriesInfo[self.timeseriesList[0]]: # relative:
+ if 'unit' in self.timeseriesInfo[
+ self.timeseriesList[0]]: # relative:
granNum = gran
unit = self.timeseriesInfo[self.timeseriesList[0]]['unit']
if self.granularityMode == GranularityMode.ONE_UNIT:
@@ -187,13 +195,13 @@
# combine all timeLabels and fill missing maps with None
# BUT this does not work properly if the datasets have
# no temporal overlap! We would need to sample all datasets
- # by a temporary dataset, I don't know how it would work with point data
+ # by a temporary dataset, I don't know how it would work with point
+ # data
if self.temporalType == TemporalType.ABSOLUTE:
timestamps = sorted(list(labelListSet), key=lambda x: x[0])
else:
timestamps = sorted(list(labelListSet), key=lambda x: x[0])
-
newMapLists = []
for mapList, labelList in zip(mapLists, labelLists):
newMapList = [None] * len(timestamps)
@@ -210,22 +218,29 @@
if self.temporalType == TemporalType.ABSOLUTE:
# ('1996-01-01 00:00:00', '1997-01-01 00:00:00', 'year'),
- formatString = UserSettings.Get(group='animation', key='temporal', subkey='format')
- timestamps = [(datetime.datetime.strftime(st, formatString),
- datetime.datetime.strftime(end, formatString)
- if end is not None else None, unit) for (st, end, unit) in timestamps]
+ formatString = UserSettings.Get(
+ group='animation', key='temporal', subkey='format')
+ timestamps = [
+ (datetime.datetime.strftime(
+ st, formatString), datetime.datetime.strftime(
+ end, formatString) if end is not None else None, unit) for (
+ st, end, unit) in timestamps]
else:
# ('15', '16', u'years'),
- timestamps = [(str(st), end if end is None else str(end), unit) for st, end, unit in timestamps]
+ timestamps = [(str(st), end if end is None else str(end), unit)
+ for st, end, unit in timestamps]
return timestamps, mapDict
def _getLabelsAndMaps(self, timeseries):
"""Returns time labels and map names (done by sampling)
for both interval and point data.
"""
- sp = tgis.dataset_factory(self.timeseriesInfo[timeseries]['etype'], timeseries)
+ sp = tgis.dataset_factory(
+ self.timeseriesInfo[timeseries]['etype'], timeseries)
if sp.is_in_db() is False:
- raise GException(_("Space time dataset <%s> not found.") % timeseries)
+ raise GException(
+ _("Space time dataset <%s> not found.") %
+ timeseries)
sp.select()
listOfMaps = []
@@ -307,7 +322,8 @@
end = tgis.string_to_datetime(end)
end = tgis.datetime_to_grass_datetime_string(end)
grassLabels.append((start, end, unit))
- if '00:00:00' not in start or (end is not None and '00:00:00' not in end):
+ if '00:00:00' not in start or (
+ end is not None and '00:00:00' not in end):
isTime = True
if not isTime:
for i, (start, end, unit) in enumerate(grassLabels):
@@ -327,7 +343,8 @@
maps = sp.get_registered_maps_as_objects()
if not sp.check_temporal_topology(maps):
- raise GException(_("Topology of Space time dataset %s is invalid." % id))
+ raise GException(
+ _("Topology of Space time dataset %s is invalid." % id))
timeseriesList.append(id)
infoDict[id] = {}
@@ -364,12 +381,22 @@
print '///////////////////////////'
gran = temp.GetGranularity()
print "granularity: " + str(gran)
- pprint (temp.GetLabelsAndMaps())
+ pprint(temp.GetLabelsAndMaps())
def createAbsoluteInterval():
- grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
- flags='p3', quiet=True)
+ grass.run_command(
+ 'g.region',
+ s=0,
+ n=80,
+ w=0,
+ e=120,
+ b=0,
+ t=50,
+ res=10,
+ res3=10,
+ flags='p3',
+ quiet=True)
grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -414,17 +441,37 @@
maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
for name, fname in zip((name1, name2), (n1, n2)):
- grass.run_command('t.create', overwrite=True, type='strds',
- temporaltype='absolute', output=name,
- title="A test with input files", descr="A test with input files")
- grass.run_command('t.register', flags='i', input=name, file=fname, overwrite=True)
+ grass.run_command(
+ 't.create',
+ overwrite=True,
+ type='strds',
+ temporaltype='absolute',
+ output=name,
+ title="A test with input files",
+ descr="A test with input files")
+ grass.run_command(
+ 't.register',
+ flags='i',
+ input=name,
+ file=fname,
+ overwrite=True)
return name1, name2
def createRelativeInterval():
- grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
- flags='p3', quiet=True)
+ grass.run_command(
+ 'g.region',
+ s=0,
+ n=80,
+ w=0,
+ e=120,
+ b=0,
+ t=50,
+ res=10,
+ res3=10,
+ flags='p3',
+ quiet=True)
grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -469,16 +516,37 @@
maps='prec_1,prec_2,prec_3,prec_4,prec_5,prec_6,'
'temp_1,temp_2,temp_3,temp_4,temp_5,temp_6')
for name, fname in zip((name1, name2), (n1, n2)):
- grass.run_command('t.create', overwrite=True, type='strds',
- temporaltype='relative', output=name,
- title="A test with input files", descr="A test with input files")
- grass.run_command('t.register', flags='i', input=name, file=fname, unit="years", overwrite=True)
+ grass.run_command(
+ 't.create',
+ overwrite=True,
+ type='strds',
+ temporaltype='relative',
+ output=name,
+ title="A test with input files",
+ descr="A test with input files")
+ grass.run_command(
+ 't.register',
+ flags='i',
+ input=name,
+ file=fname,
+ unit="years",
+ overwrite=True)
return name1, name2
def createAbsolutePoint():
- grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
- flags='p3', quiet=True)
+ grass.run_command(
+ 'g.region',
+ s=0,
+ n=80,
+ w=0,
+ e=120,
+ b=0,
+ t=50,
+ res=10,
+ res3=10,
+ flags='p3',
+ quiet=True)
grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -499,17 +567,37 @@
)
fd.close()
name = 'abspoint'
- grass.run_command('t.create', overwrite=True, type='strds',
- temporaltype='absolute', output=name,
- title="A test with input files", descr="A test with input files")
+ grass.run_command(
+ 't.create',
+ overwrite=True,
+ type='strds',
+ temporaltype='absolute',
+ output=name,
+ title="A test with input files",
+ descr="A test with input files")
- grass.run_command('t.register', flags='i', input=name, file=n1, overwrite=True)
+ grass.run_command(
+ 't.register',
+ flags='i',
+ input=name,
+ file=n1,
+ overwrite=True)
return name
def createRelativePoint():
- grass.run_command('g.region', s=0, n=80, w=0, e=120, b=0, t=50, res=10, res3=10,
- flags='p3', quiet=True)
+ grass.run_command(
+ 'g.region',
+ s=0,
+ n=80,
+ w=0,
+ e=120,
+ b=0,
+ t=50,
+ res=10,
+ res3=10,
+ flags='p3',
+ quiet=True)
grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True)
grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True)
@@ -530,11 +618,21 @@
)
fd.close()
name = 'relpoint'
- grass.run_command('t.create', overwrite=True, type='strds',
- temporaltype='relative', output=name,
- title="A test with input files", descr="A test with input files")
+ grass.run_command(
+ 't.create',
+ overwrite=True,
+ type='strds',
+ temporaltype='relative',
+ output=name,
+ title="A test with input files",
+ descr="A test with input files")
- grass.run_command('t.register', unit="day", input=name, file=n1, overwrite=True)
+ grass.run_command(
+ 't.register',
+ unit="day",
+ input=name,
+ file=n1,
+ overwrite=True)
return name
if __name__ == '__main__':
Modified: grass/trunk/gui/wxpython/animation/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/animation/toolbars.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/toolbars.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,35 +25,55 @@
from animation.anim import ReplayMode
ganimIcons = {
- 'speed': MetaIcon(img='move', label=_("Change animation speed")),
- 'playForward': MetaIcon(img='execute', label=_("Play forward")),
- 'playBack': MetaIcon(img='player-back', label=_("Play back")),
- 'stop': MetaIcon(img='player-stop', label=_("Stop")),
- 'pause': MetaIcon(img='player-pause', label=_("Pause")),
- 'oneDirectionReplay': MetaIcon(img='redraw', label=_("Repeat")),
- 'bothDirectionReplay': MetaIcon(img='player-repeat-back-forward',
- label=_("Play back and forward")),
- 'addAnimation': MetaIcon(img='layer-add', label=_("Add new animation"),
- desc=_("Add new animation")),
- 'editAnimation': MetaIcon(img='layer-more', label=_("Add, edit or remove animation"),
- desc=_("Add, edit or remove animation")),
- 'exportAnimation': MetaIcon(img='layer-export', label=_("Export animation"),
- desc=_("Export animation"))
-}
+ 'speed': MetaIcon(
+ img='move',
+ label=_("Change animation speed")),
+ 'playForward': MetaIcon(
+ img='execute',
+ label=_("Play forward")),
+ 'playBack': MetaIcon(
+ img='player-back',
+ label=_("Play back")),
+ 'stop': MetaIcon(
+ img='player-stop',
+ label=_("Stop")),
+ 'pause': MetaIcon(
+ img='player-pause',
+ label=_("Pause")),
+ 'oneDirectionReplay': MetaIcon(
+ img='redraw',
+ label=_("Repeat")),
+ 'bothDirectionReplay': MetaIcon(
+ img='player-repeat-back-forward',
+ label=_("Play back and forward")),
+ 'addAnimation': MetaIcon(
+ img='layer-add',
+ label=_("Add new animation"),
+ desc=_("Add new animation")),
+ 'editAnimation': MetaIcon(
+ img='layer-more',
+ label=_("Add, edit or remove animation"),
+ desc=_("Add, edit or remove animation")),
+ 'exportAnimation': MetaIcon(
+ img='layer-export',
+ label=_("Export animation"),
+ desc=_("Export animation"))}
SIMPLE_LMGR_STDS = 256
simpleLmgrIcons = {
- 'addSeries': MetaIcon(img='mapset-add',
- label=_("Add space-time dataset or series of map layers"),
- desc=_("Add space-time dataset or series of map layers for animation")),
+ 'addSeries': MetaIcon(
+ img='mapset-add',
+ label=_("Add space-time dataset or series of map layers"),
+ desc=_("Add space-time dataset or series of map layers for animation")),
}
class MainToolbar(BaseToolbar):
"""Main toolbar (data management)
"""
+
def __init__(self, parent):
"""Main toolbar constructor
"""
@@ -69,20 +89,21 @@
# BaseIcons are a set of often used icons. It is possible
# to reuse icons in ./trunk/gui/icons/grass or add new ones there.
icons = ganimIcons
- return self._getToolbarData((("addAnimation", icons["addAnimation"],
- self.parent.OnAddAnimation),
- ("editAnimation", icons["editAnimation"],
- self.parent.OnEditAnimation),
- ("reload", BaseIcons["render"],
- self.parent.Reload),
- ("exportAnimation", icons["exportAnimation"],
- self.parent.OnExportAnimation)
- ))
+ return self._getToolbarData(
+ (("addAnimation", icons["addAnimation"],
+ self.parent.OnAddAnimation),
+ ("editAnimation", icons["editAnimation"],
+ self.parent.OnEditAnimation),
+ ("reload", BaseIcons["render"],
+ self.parent.Reload),
+ ("exportAnimation", icons["exportAnimation"],
+ self.parent.OnExportAnimation)))
class AnimationToolbar(BaseToolbar):
"""Animation toolbar (to control animation)
"""
+
def __init__(self, parent):
"""Animation toolbar constructor
"""
@@ -101,26 +122,23 @@
# BaseIcons are a set of often used icons. It is possible
# to reuse icons in ./trunk/gui/icons/grass or add new ones there.
icons = ganimIcons
- return self._getToolbarData((("playBack", icons["playBack"],
- self.OnPlayBack),
- ("playForward", icons["playForward"],
- self.OnPlayForward),
- ("pause", icons["pause"],
- self.OnPause,
- wx.ITEM_CHECK),
- ("stop", icons["stop"],
- self.OnStop),
- (None, ),
- ("oneDirectionReplay", icons["oneDirectionReplay"],
- self.OnOneDirectionReplay,
- wx.ITEM_CHECK),
- ("bothDirectionReplay", icons["bothDirectionReplay"],
- self.OnBothDirectionReplay,
- wx.ITEM_CHECK),
- (None, ),
- ("adjustSpeed", icons['speed'],
- self.parent.OnAdjustSpeed)
- ))
+ return self._getToolbarData(
+ (("playBack", icons["playBack"],
+ self.OnPlayBack),
+ ("playForward", icons["playForward"],
+ self.OnPlayForward),
+ ("pause", icons["pause"],
+ self.OnPause, wx.ITEM_CHECK),
+ ("stop", icons["stop"],
+ self.OnStop),
+ (None,),
+ ("oneDirectionReplay", icons["oneDirectionReplay"],
+ self.OnOneDirectionReplay, wx.ITEM_CHECK),
+ ("bothDirectionReplay", icons["bothDirectionReplay"],
+ self.OnBothDirectionReplay, wx.ITEM_CHECK),
+ (None,),
+ ("adjustSpeed", icons['speed'],
+ self.parent.OnAdjustSpeed)))
def OnPlayForward(self, event):
self.PlayForward()
@@ -171,7 +189,8 @@
# if not self.GetToolState(self.oneDirectionReplay) and \
# not self.GetToolState(self.bothDirectionReplay):
- # self.EnableTool(self.playBack, False) # assuming that stop rewinds to the beginning
+ # self.EnableTool(self.playBack, False) # assuming that stop rewinds to
+ # the beginning
def OnOneDirectionReplay(self, event):
if event.IsChecked():
@@ -204,6 +223,7 @@
class MiscToolbar(BaseToolbar):
"""Toolbar with miscellaneous tools related to app
"""
+
def __init__(self, parent):
"""Toolbar constructor
"""
@@ -228,6 +248,7 @@
"""Simple layer manager toolbar for animation tool.
Allows adding space-time dataset or series of maps.
"""
+
def __init__(self, parent, lmgrStyle):
SimpleLmgrToolbar.__init__(self, parent, lmgrStyle)
Modified: grass/trunk/gui/wxpython/animation/utils.py
===================================================================
--- grass/trunk/gui/wxpython/animation/utils.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/animation/utils.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -66,7 +66,9 @@
if nameShort in trastDict[mapset]:
return timeseries
else:
- raise GException(_("Space time dataset <%s> not found.") % timeseries)
+ raise GException(
+ _("Space time dataset <%s> not found.") %
+ timeseries)
mapsets = tgis.get_tgis_c_library_interface().available_mapsets()
for mapset in mapsets:
@@ -200,7 +202,8 @@
raise GException(_("The number of maps to animate has to be "
"the same for each map series."))
- if timeseriesList and list(count)[0] != list(timeseriesInfo['count'])[0]:
+ if timeseriesList and list(count)[0] != list(
+ timeseriesInfo['count'])[0]:
raise GException(_("The number of maps to animate has to be "
"the same as the number of maps in temporal dataset."))
@@ -260,7 +263,13 @@
def WxImageToPil(image):
"""Converts wx.Image to PIL image"""
pilImage = Image.new('RGB', (image.GetWidth(), image.GetHeight()))
- getattr(pilImage, "frombytes", getattr(pilImage, "fromstring"))(image.GetData())
+ getattr(
+ pilImage,
+ "frombytes",
+ getattr(
+ pilImage,
+ "fromstring"))(
+ image.GetData())
return pilImage
@@ -318,9 +327,12 @@
if mapLayer:
try:
idx = cmd.index('layer')
- cmd[idx] = 'layer={layer}'.format(layer=mapLayer)
+ cmd[idx] = 'layer={layer}'.format(
+ layer=mapLayer)
except ValueError:
- cmd.append('layer={layer}'.format(layer=mapLayer))
+ cmd.append(
+ 'layer={layer}'.format(
+ layer=mapLayer))
cmds.append(cmd[:])
cmdsForComposition.append(cmds)
else:
Modified: grass/trunk/gui/wxpython/core/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/core/__init__.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/__init__.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -13,4 +13,4 @@
'utils',
'globalvar',
'giface',
- ]
+]
Modified: grass/trunk/gui/wxpython/core/debug.py
===================================================================
--- grass/trunk/gui/wxpython/core/debug.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/debug.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -10,7 +10,7 @@
from core.debug import Debug
Debug.msg (3, 'debug message')
@endcode
-
+
(C) 2007-2009, 2011 by the GRASS Development Team
This program is free software under the GNU General Public License
@@ -24,16 +24,18 @@
import grass.script as grass
+
class DebugMsg:
"""wxGUI debugging
-
+
g.gisenv set=WX_DEBUG=[0-5]
"""
+
def __init__(self):
# default level
self.debuglevel = 0
-
+
self.SetLevel()
def SetLevel(self):
@@ -42,11 +44,14 @@
try:
self.debuglevel = int(grass.gisenv().get('WX_DEBUG', 0))
if self.debuglevel < 0 or self.debuglevel > 5:
- raise ValueError(_("Wx debug level {}.").format(self.debuglevel))
+ raise ValueError(
+ _("Wx debug level {}.").format(
+ self.debuglevel))
except ValueError as e:
self.debuglevel = 0
- sys.stderr.write(_("WARNING: Ignoring unsupported wx debug level (must be >=0 and <=5). {}\n").format(e))
-
+ sys.stderr.write(
+ _("WARNING: Ignoring unsupported wx debug level (must be >=0 and <=5). {}\n").format(e))
+
def msg(self, level, message, *args):
"""Print debug message
@@ -57,13 +62,13 @@
# self.SetLevel()
if self.debuglevel > 0 and level > 0 and level <= self.debuglevel:
if args:
- sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) + \
- message % args + os.linesep)
+ sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) +
+ message % args + os.linesep)
else:
- sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) + \
- message + os.linesep)
- sys.stderr.flush() # force flush (required for MS Windows)
-
+ sys.stderr.write("GUI D%d/%d: " % (level, self.debuglevel) +
+ message + os.linesep)
+ sys.stderr.flush() # force flush (required for MS Windows)
+
def GetLevel(self):
"""Return current GUI debug level"""
return self.debuglevel
Modified: grass/trunk/gui/wxpython/core/gcmd.py
===================================================================
--- grass/trunk/gui/wxpython/core/gcmd.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gcmd.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -46,14 +46,18 @@
from grass.script import core as grass
-from core import globalvar
+from core import globalvar
from core.debug import Debug
# cannot import from the core.utils module to avoid cross dependencies
try:
# intended to be used also outside this module
import gettext
- _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+ _ = gettext.translation(
+ 'grasswxpy',
+ os.path.join(
+ os.getenv("GISBASE"),
+ 'locale')).ugettext
except IOError:
# using no translation silently
def null_gettext(string):
@@ -63,38 +67,41 @@
def DecodeString(string):
"""Decode string using system encoding
-
+
:param string: string to be decoded
-
+
:return: decoded string
"""
if not string:
return string
-
+
if _enc:
Debug.msg(5, "DecodeString(): enc=%s" % _enc)
return string.decode(_enc)
-
+
return string
+
def EncodeString(string):
"""Return encoded string using system locales
-
+
:param string: string to be encoded
-
+
:return: encoded string
"""
if not string:
return string
-
+
if _enc:
Debug.msg(5, "EncodeString(): enc=%s" % _enc)
return string.encode(_enc)
-
+
return string
+
class GError:
- def __init__(self, message, parent = None, caption = None, showTraceback = True):
+
+ def __init__(self, message, parent=None, caption=None, showTraceback=True):
"""Show error message window
:param message: error message
@@ -109,43 +116,49 @@
if exc_traceback:
exception = traceback.format_exc()
reason = exception.splitlines()[-1].split(':', 1)[-1].strip()
-
+
if Debug.GetLevel() > 0 and exc_traceback:
sys.stderr.write(exception)
-
+
if showTraceback and exc_traceback:
- wx.MessageBox(parent = parent,
- message = message + '\n\n%s: %s\n\n%s' % \
- (_('Reason'),
- reason, exception),
- caption = caption,
- style = style)
+ wx.MessageBox(parent=parent,
+ message=message + '\n\n%s: %s\n\n%s' %
+ (_('Reason'),
+ reason, exception),
+ caption=caption,
+ style=style)
else:
- wx.MessageBox(parent = parent,
- message = message,
- caption = caption,
- style = style)
+ wx.MessageBox(parent=parent,
+ message=message,
+ caption=caption,
+ style=style)
+
class GWarning:
- def __init__(self, message, parent = None):
+
+ def __init__(self, message, parent=None):
caption = _('Warning')
style = wx.OK | wx.ICON_WARNING | wx.CENTRE
- wx.MessageBox(parent = parent,
- message = message,
- caption = caption,
- style = style)
-
+ wx.MessageBox(parent=parent,
+ message=message,
+ caption=caption,
+ style=style)
+
+
class GMessage:
- def __init__(self, message, parent = None):
+
+ def __init__(self, message, parent=None):
caption = _('Message')
style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE
- wx.MessageBox(parent = parent,
- message = message,
- caption = caption,
- style = style)
+ wx.MessageBox(parent=parent,
+ message=message,
+ caption=caption,
+ style=style)
+
class GException(Exception):
- def __init__(self, value = ''):
+
+ def __init__(self, value=''):
self.value = value
def __str__(self):
@@ -154,8 +167,10 @@
def __unicode__(self):
return self.value
+
class Popen(subprocess.Popen):
"""Subclass subprocess.Popen"""
+
def __init__(self, args, **kwargs):
if subprocess.mswindows:
args = map(EncodeString, args)
@@ -190,14 +205,14 @@
args[i] = k + v
subprocess.Popen.__init__(self, args, **kwargs)
-
- def recv(self, maxsize = None):
+
+ def recv(self, maxsize=None):
return self._recv('stdout', maxsize)
-
- def recv_err(self, maxsize = None):
+
+ def recv_err(self, maxsize=None):
return self._recv('stderr', maxsize)
- def send_recv(self, input = '', maxsize = None):
+ def send_recv(self, input='', maxsize=None):
return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
def get_conn_maxsize(self, which, maxsize):
@@ -206,7 +221,7 @@
elif maxsize < 1:
maxsize = 1
return getattr(self, which), maxsize
-
+
def _close(self, which):
getattr(self, which).close()
setattr(self, which, None)
@@ -219,7 +234,7 @@
return (0 != win32api.TerminateProcess(handle, 0))
else:
try:
- os.kill(-self.pid, signal.SIGTERM) # kill whole group
+ os.kill(-self.pid, signal.SIGTERM) # kill whole group
except OSError:
pass
@@ -244,7 +259,7 @@
conn, maxsize = self.get_conn_maxsize(which, maxsize)
if conn is None:
return None
-
+
try:
x = msvcrt.get_osfhandle(conn.fileno())
(read, nAvail, nMessage) = PeekNamedPipe(x, 0)
@@ -258,7 +273,7 @@
if why[0] in (109, errno.ESHUTDOWN):
return self._close(which)
raise
-
+
if self.universal_newlines:
read = self._translate_newlines(read)
return read
@@ -274,7 +289,7 @@
try:
written = os.write(self.stdin.fileno(), input)
except OSError as why:
- if why[0] == errno.EPIPE: #broken pipe
+ if why[0] == errno.EPIPE: # broken pipe
return self._close('stdin')
raise
@@ -284,20 +299,20 @@
conn, maxsize = self.get_conn_maxsize(which, maxsize)
if conn is None:
return None
-
+
flags = fcntl.fcntl(conn, fcntl.F_GETFL)
if not conn.closed:
- fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-
+ fcntl.fcntl(conn, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
try:
if not select.select([conn], [], [], 0)[0]:
return ''
-
+
r = conn.read(maxsize)
-
+
if not r:
return self._close(which)
-
+
if self.universal_newlines:
r = self._translate_newlines(r)
return r
@@ -307,10 +322,11 @@
message = "Other end disconnected!"
-def recv_some(p, t = .1, e = 1, tr = 5, stderr = 0):
+
+def recv_some(p, t=.1, e=1, tr=5, stderr=0):
if tr < 1:
tr = 1
- x = time.time()+t
+ x = time.time() + t
y = []
r = ''
pr = p.recv
@@ -326,9 +342,10 @@
elif r:
y.append(r)
else:
- time.sleep(max((x-time.time())/tr, 0))
+ time.sleep(max((x - time.time()) / tr, 0))
return ''.join(y)
-
+
+
def send_all(p, data):
while len(data):
sent = p.send(data)
@@ -336,6 +353,7 @@
raise Exception(message)
data = buffer(data, sent)
+
class Command:
"""Run command in separate thread. Used for commands launched
on the background.
@@ -352,9 +370,10 @@
else:
print 'FAILURE (%d)' % cmd.returncode
"""
- def __init__ (self, cmd, stdin = None,
- verbose = None, wait = True, rerr = False,
- stdout = None, stderr = None):
+
+ def __init__(self, cmd, stdin=None,
+ verbose=None, wait=True, rerr=False,
+ stdout=None, stderr=None):
"""
:param cmd: command given as list
:param stdin: standard input stream
@@ -391,7 +410,7 @@
self.cmdThread = CommandThread(cmd, stdin,
stdout, stderr)
self.cmdThread.start()
-
+
if wait:
self.cmdThread.join()
if self.cmdThread.module:
@@ -404,33 +423,39 @@
self.returncode = None
if self.returncode is not None:
- Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" % \
- (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
+ Debug.msg(
+ 3, "Command(): cmd='%s', wait=%s, returncode=%d, alive=%s" %
+ (' '.join(cmd), wait, self.returncode, self.cmdThread.isAlive()))
if rerr is not None and self.returncode != 0:
- if rerr is False: # GUI dialog
- raise GException("%s '%s'%s%s%s %s%s" % \
- (_("Execution failed:"),
- ' '.join(self.cmd),
- os.linesep, os.linesep,
- _("Details:"),
- os.linesep,
- _("Error: ") + self.__GetError()))
- elif rerr == sys.stderr: # redirect message to sys
- stderr.write("Execution failed: '%s'" % (' '.join(self.cmd)))
- stderr.write("%sDetails:%s%s" % (os.linesep,
- _("Error: ") + self.__GetError(),
- os.linesep))
+ if rerr is False: # GUI dialog
+ raise GException("%s '%s'%s%s%s %s%s" %
+ (_("Execution failed:"),
+ ' '.join(self.cmd),
+ os.linesep, os.linesep,
+ _("Details:"),
+ os.linesep,
+ _("Error: ") + self.__GetError()))
+ elif rerr == sys.stderr: # redirect message to sys
+ stderr.write("Execution failed: '%s'" %
+ (' '.join(self.cmd)))
+ stderr.write(
+ "%sDetails:%s%s" %
+ (os.linesep,
+ _("Error: ") +
+ self.__GetError(),
+ os.linesep))
else:
- pass # nop
+ pass # nop
else:
- Debug.msg (3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" % \
- (' '.join(cmd), wait, self.cmdThread.isAlive()))
+ Debug.msg(
+ 3, "Command(): cmd='%s', wait=%s, returncode=?, alive=%s" %
+ (' '.join(cmd), wait, self.cmdThread.isAlive()))
if verbose_orig:
os.environ["GRASS_VERBOSE"] = verbose_orig
elif "GRASS_VERBOSE" in os.environ:
del os.environ["GRASS_VERBOSE"]
-
+
def __ReadOutput(self, stream):
"""Read stream and return list of lines
@@ -449,7 +474,7 @@
lineList.append(line)
return lineList
-
+
def __ReadErrOutput(self):
"""Read standard error output and return list of lines"""
return self.__ReadOutput(self.cmdThread.module.stderr)
@@ -465,27 +490,27 @@
else:
lines = self.cmdThread.error.strip('%s' % os.linesep). \
split('%s' % os.linesep)
-
+
msg = []
- type = None
+ type = None
content = ""
for line in lines:
if len(line) == 0:
continue
- if 'GRASS_' in line: # error or warning
- if 'GRASS_INFO_WARNING' in line: # warning
+ if 'GRASS_' in line: # error or warning
+ if 'GRASS_INFO_WARNING' in line: # warning
type = "WARNING"
- elif 'GRASS_INFO_ERROR' in line: # error
+ elif 'GRASS_INFO_ERROR' in line: # error
type = "ERROR"
- elif 'GRASS_INFO_END': # end of message
+ elif 'GRASS_INFO_END': # end of message
msg.append((type, content))
type = None
content = ""
-
+
if type:
content += line.split(':', 1)[1].strip()
- else: # stderr
+ else: # stderr
msg.append((None, line.strip()))
return msg
@@ -494,53 +519,55 @@
"""Get error message or ''"""
if not self.cmdThread.module:
return _("Unable to exectute command: '%s'") % ' '.join(self.cmd)
-
+
for type, msg in self.__ProcessStdErr():
if type == 'ERROR':
if _enc:
return unicode(msg, _enc)
return msg
-
+
return ''
-
+
+
class CommandThread(Thread):
"""Create separate thread for command. Used for commands launched
on the background."""
- def __init__ (self, cmd, env = None, stdin = None,
- stdout = sys.stdout, stderr = sys.stderr):
+
+ def __init__(self, cmd, env=None, stdin=None,
+ stdout=sys.stdout, stderr=sys.stderr):
"""
:param cmd: command (given as list)
:param env: environmental variables
- :param stdin: standard input stream
+ :param stdin: standard input stream
:param stdout: redirect standard output or None
:param stderr: redirect standard error output or None
"""
Thread.__init__(self)
-
- self.cmd = cmd
- self.stdin = stdin
+
+ self.cmd = cmd
+ self.stdin = stdin
self.stdout = stdout
self.stderr = stderr
- self.env = env
-
+ self.env = env
+
self.module = None
- self.error = ''
-
+ self.error = ''
+
self._want_abort = False
self.aborted = False
-
+
self.setDaemon(True)
-
+
# set message formatting
self.message_format = os.getenv("GRASS_MESSAGE_FORMAT")
os.environ["GRASS_MESSAGE_FORMAT"] = "gui"
-
+
def __del__(self):
if self.message_format:
os.environ["GRASS_MESSAGE_FORMAT"] = self.message_format
else:
del os.environ["GRASS_MESSAGE_FORMAT"]
-
+
def run(self):
"""Run command"""
if len(self.cmd) == 0:
@@ -565,27 +592,27 @@
args[0] = grass.get_real_command(args[0])
if args[0].endswith('.py'):
args.insert(0, sys.executable)
-
+
try:
self.module = Popen(args,
- stdin = subprocess.PIPE,
- stdout = subprocess.PIPE,
- stderr = subprocess.PIPE,
- shell = sys.platform == "win32",
- env = self.env)
-
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ shell=sys.platform == "win32",
+ env=self.env)
+
except OSError as e:
self.error = str(e)
print >> sys.stderr, e
return 1
-
- if self.stdin: # read stdin if requested ...
+
+ if self.stdin: # read stdin if requested ...
self.module.stdin.write(self.stdin)
self.module.stdin.close()
-
+
# redirect standard outputs...
self._redirect_stream()
-
+
def _redirect_stream(self):
"""Redirect stream"""
if self.stdout:
@@ -593,44 +620,45 @@
out_fileno = self.module.stdout.fileno()
if not subprocess.mswindows:
flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
- fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-
+ fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
if self.stderr:
# make module stdout/stderr non-blocking
out_fileno = self.module.stderr.fileno()
if not subprocess.mswindows:
flags = fcntl.fcntl(out_fileno, fcntl.F_GETFL)
- fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags| os.O_NONBLOCK)
-
+ fcntl.fcntl(out_fileno, fcntl.F_SETFL, flags | os.O_NONBLOCK)
+
# wait for the process to end, sucking in stuff until it does end
while self.module.poll() is None:
- if self._want_abort: # abort running process
+ if self._want_abort: # abort running process
self.module.terminate()
self.aborted = True
- return
+ return
if self.stdout:
- line = recv_some(self.module, e = 0, stderr = 0)
+ line = recv_some(self.module, e=0, stderr=0)
self.stdout.write(line)
if self.stderr:
- line = recv_some(self.module, e = 0, stderr = 1)
+ line = recv_some(self.module, e=0, stderr=1)
self.stderr.write(line)
if len(line) > 0:
self.error = line
# get the last output
if self.stdout:
- line = recv_some(self.module, e = 0, stderr = 0)
+ line = recv_some(self.module, e=0, stderr=0)
self.stdout.write(line)
if self.stderr:
- line = recv_some(self.module, e = 0, stderr = 1)
+ line = recv_some(self.module, e=0, stderr=1)
self.stderr.write(line)
if len(line) > 0:
self.error = line
-
+
def abort(self):
"""Abort running process, used by main thread to signal an abort"""
self._want_abort = True
-
+
+
def _formatMsg(text):
"""Format error messages for dialogs
"""
@@ -648,12 +676,13 @@
return message
else:
message += line.strip() + '\n'
-
+
return message
-def RunCommand(prog, flags = "", overwrite = False, quiet = False,
- verbose = False, parent = None, read = False,
- parse = None, stdin = None, getErrorMsg = False, **kwargs):
+
+def RunCommand(prog, flags="", overwrite=False, quiet=False,
+ verbose=False, parent=None, read=False,
+ parse=None, stdin=None, getErrorMsg=False, **kwargs):
"""Run GRASS command
:param prog: program to run
@@ -665,7 +694,7 @@
:param stdin: stdin or None
:param getErrorMsg: get error messages on failure
:param kwargs: program parameters
-
+
:return: returncode (read == False and getErrorMsg == False)
:return: returncode, messages (read == False and getErrorMsg == True)
:return: stdout (read == True and getErrorMsg == False)
@@ -674,50 +703,50 @@
"""
cmdString = ' '.join(grass.make_command(prog, flags, overwrite,
quiet, verbose, **kwargs))
-
+
Debug.msg(1, "gcmd.RunCommand(): %s" % cmdString)
-
+
kwargs['stderr'] = subprocess.PIPE
-
+
if read:
kwargs['stdout'] = subprocess.PIPE
-
+
if stdin:
kwargs['stdin'] = subprocess.PIPE
if parent:
messageFormat = os.getenv('GRASS_MESSAGE_FORMAT', 'gui')
os.environ['GRASS_MESSAGE_FORMAT'] = 'standard'
-
+
start = time.time()
-
+
ps = grass.start_command(prog, flags, overwrite, quiet, verbose, **kwargs)
-
+
if stdin:
ps.stdin.write(stdin)
ps.stdin.close()
ps.stdin = None
-
+
stdout, stderr = map(DecodeString, ps.communicate())
-
- if parent: # restore previous settings
+
+ if parent: # restore previous settings
os.environ['GRASS_MESSAGE_FORMAT'] = messageFormat
-
+
ret = ps.returncode
- Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" % \
- (ret, (time.time() - start)))
-
+ Debug.msg(1, "gcmd.RunCommand(): get return code %d (%.6f sec)" %
+ (ret, (time.time() - start)))
+
if ret != 0:
if stderr:
Debug.msg(2, "gcmd.RunCommand(): error %s" % stderr)
else:
Debug.msg(2, "gcmd.RunCommand(): nothing to print ???")
-
+
if parent:
- GError(parent = parent,
- caption = _("Error in %s") % prog,
- message = stderr)
-
+ GError(parent=parent,
+ caption=_("Error in %s") % prog,
+ message=stderr)
+
if not read:
if not getErrorMsg:
return ret
@@ -728,21 +757,22 @@
Debug.msg(3, "gcmd.RunCommand(): return stdout\n'%s'" % stdout)
else:
Debug.msg(3, "gcmd.RunCommand(): return stdout = None")
-
+
if parse:
stdout = parse(stdout)
-
+
if not getErrorMsg:
return stdout
-
+
if read and getErrorMsg:
return ret, stdout, _formatMsg(stderr)
-
+
return stdout, _formatMsg(stderr)
-def GetDefaultEncoding(forceUTF8 = False):
+
+def GetDefaultEncoding(forceUTF8=False):
"""Get default system encoding
-
+
:param bool forceUTF8: force 'UTF-8' if encoding is not defined
:return: system encoding (can be None)
@@ -750,8 +780,8 @@
enc = locale.getdefaultlocale()[1]
if forceUTF8 and (enc is None or enc == 'UTF8'):
return 'UTF-8'
-
+
Debug.msg(1, "GetSystemEncoding(): %s" % enc)
return enc
-_enc = GetDefaultEncoding() # define as global variable
+_enc = GetDefaultEncoding() # define as global variable
Modified: grass/trunk/gui/wxpython/core/gconsole.py
===================================================================
--- grass/trunk/gui/wxpython/core/gconsole.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gconsole.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,7 +33,7 @@
from wx.lib.newevent import NewEvent
import grass.script as grass
-from grass.script import task as gtask
+from grass.script import task as gtask
from grass.pydispatch.signal import Signal
@@ -116,7 +116,8 @@
os.environ['GRASS_MESSAGE_FORMAT'] = 'gui'
while True:
requestId, args, kwds = self.requestQ.get()
- for key in ('callable', 'onDone', 'onPrepare', 'userData', 'addLayer', 'notification'):
+ for key in ('callable', 'onDone', 'onPrepare',
+ 'userData', 'addLayer', 'notification'):
if key in kwds:
vars()[key] = kwds[key]
del kwds[key]
@@ -191,7 +192,8 @@
argsColor[0] = ['r.colors',
'map=%s' % mapName,
'color=%s' % colorTable]
- self.requestCmdColor = vars()['callable'](*argsColor, **kwds)
+ self.requestCmdColor = vars()['callable'](
+ *argsColor, **kwds)
self.resultQ.put((requestId, self.requestCmdColor.run()))
if self.receiver:
@@ -217,6 +219,7 @@
if self.requestQ.empty():
self._want_abort_all = False
+
class GStdout:
"""GConsole standard output
@@ -228,6 +231,7 @@
Copyright: (c) 2005-2007 Jean-Michel Fauth
Licence: GPL
"""
+
def __init__(self, receiver):
"""
:param receiver: event receiver (used in PostEvent)
@@ -261,6 +265,7 @@
Copyright: (c) 2005-2007 Jean-Michel Fauth
Licence: GPL
"""
+
def __init__(self, receiver):
"""
:param receiver: event receiver (used in PostEvent)
@@ -334,6 +339,7 @@
class GConsole(wx.EvtHandler):
"""
"""
+
def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None):
"""
:param guiparent: parent window for created GUI objects
@@ -404,9 +410,10 @@
:param notification: form of notification
"""
self.writeLog.emit(text=text, wrap=wrap,
- notification=notification)
+ notification=notification)
- def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+ def WriteCmdLog(self, text, pid=None,
+ notification=Notification.MAKE_VISIBLE):
"""Write message in selected style
:param text: message to be printed
@@ -456,17 +463,17 @@
# update history file
self.UpdateHistoryFile(' '.join(command))
-
+
if command[0] in globalvar.grassCmd:
# send GRASS command without arguments to GUI command interface
# except ignored commands (event is emitted)
if self._ignoredCmdPattern and \
- re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
- '--help' not in command and '--ui' not in command:
+ re.compile(self._ignoredCmdPattern).search(' '.join(command)) and \
+ '--help' not in command and '--ui' not in command:
event = gIgnoredCmdRun(cmd=command)
wx.PostEvent(self, event)
return
-
+
else:
# other GRASS commands (r|v|g|...)
try:
@@ -487,11 +494,16 @@
p.get('element', '') == 'file' and \
p.get('age', 'new') == 'old' and \
p.get('value', '') == '-':
- GError(parent=self._guiparent,
- message=_("Unable to run command:\n%(cmd)s\n\n"
- "Option <%(opt)s>: read from standard input is not "
- "supported by wxGUI") % {'cmd': ' '.join(command),
- 'opt': p.get('name', '')})
+ GError(
+ parent=self._guiparent,
+ message=_(
+ "Unable to run command:\n%(cmd)s\n\n"
+ "Option <%(opt)s>: read from standard input is not "
+ "supported by wxGUI") % {
+ 'cmd': ' '.join(command),
+ 'opt': p.get(
+ 'name',
+ '')})
return
if len(command) == 1:
@@ -501,27 +513,33 @@
pyFile = command[0]
if sys.platform == 'win32':
pyFile += '.py'
- pyPath = os.path.join(os.environ['GISBASE'], 'scripts', pyFile)
+ pyPath = os.path.join(
+ os.environ['GISBASE'], 'scripts', pyFile)
if not os.path.exists(pyPath):
- pyPath = os.path.join(os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile)
+ pyPath = os.path.join(
+ os.environ['GRASS_ADDON_BASE'], 'scripts', pyFile)
if not os.path.exists(pyPath):
- GError(parent=self._guiparent,
- message=_("Module <%s> not found.") % command[0])
- pymodule = imp.load_source(command[0].replace('.', '_'), pyPath)
+ GError(
+ parent=self._guiparent,
+ message=_("Module <%s> not found.") %
+ command[0])
+ pymodule = imp.load_source(
+ command[0].replace('.', '_'), pyPath)
pymain = inspect.getargspec(pymodule.main)
if pymain and 'giface' in pymain.args:
pymodule.main(self._giface)
return
-
+
if hasParams and command[0] != 'v.krige':
# no arguments given
try:
- GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
+ GUI(parent=self._guiparent,
+ giface=self._giface).ParseCommand(command)
except GException as e:
print >> sys.stderr, e
-
+
return
-
+
# activate computational region (set with g.region)
# for all non-display commands.
if compReg:
@@ -539,7 +557,8 @@
notification=notification)
self.cmdOutputTimer.Start(50)
- # deactivate computational region and return to display settings
+ # deactivate computational region and return to display
+ # settings
if compReg and tmpreg:
os.environ["GRASS_REGION"] = tmpreg
else:
@@ -569,7 +588,7 @@
sfile.close()
except IOError:
pass
-
+
if len(command) == 1 and not skipInterface:
try:
task = gtask.parse_interface(command[0])
@@ -580,7 +599,8 @@
if task:
# process GRASS command without argument
- GUI(parent=self._guiparent, giface=self._giface).ParseCommand(command)
+ GUI(parent=self._guiparent,
+ giface=self._giface).ParseCommand(command)
else:
self.cmdThread.RunCmd(command,
stdout=self.cmdStdOut,
@@ -631,8 +651,8 @@
stime = _("%d sec") % int(ctime)
else:
mtime = int(ctime / 60)
- stime = _("%(min)d min %(sec)d sec") % {'min': mtime,
- 'sec': int(ctime - (mtime * 60))}
+ stime = _("%(min)d min %(sec)d sec") % {
+ 'min': mtime, 'sec': int(ctime - (mtime * 60))}
except KeyError:
# stopped deamon
stime = _("unknown")
@@ -676,14 +696,17 @@
name = task.get_name()
for p in task.get_options()['params']:
prompt = p.get('prompt', '')
- if prompt in ('raster', 'vector', 'raster_3d') and p.get('value', None):
- if p.get('age', 'old') == 'new' or \
- name in ('r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
+ if prompt in (
+ 'raster', 'vector', 'raster_3d') and p.get(
+ 'value', None):
+ if p.get('age', 'old') == 'new' or name in (
+ 'r.colors', 'r3.colors', 'v.colors', 'v.proj', 'r.proj'):
# if multiple maps (e.g. r.series.interp), we need add each
if p.get('multiple', False):
lnames = p.get('value').split(',')
# in case multiple input (old) maps in r.colors
- # we don't want to rerender it multiple times! just once
+ # we don't want to rerender it multiple times! just
+ # once
if p.get('age', 'old') == 'old':
lnames = lnames[0:1]
else:
@@ -691,11 +714,13 @@
for lname in lnames:
if '@' not in lname:
lname += '@' + grass.gisenv()['MAPSET']
- if grass.find_file(lname, element=p.get('element'))['fullname']:
- self.mapCreated.emit(name=lname, ltype=prompt, add=event.addLayer)
+ if grass.find_file(lname, element=p.get('element'))[
+ 'fullname']:
+ self.mapCreated.emit(
+ name=lname, ltype=prompt, add=event.addLayer)
if name == 'r.mask':
self.updateMap.emit()
-
+
event.Skip()
def OnProcessPendingOutputWindowEvents(self, event):
@@ -703,7 +728,7 @@
def UpdateHistoryFile(self, command):
"""Update history file
-
+
:param command: the command given as a string
"""
env = grass.gisenv()
@@ -714,17 +739,16 @@
'.bash_history')
fileHistory = codecs.open(filePath, encoding='utf-8', mode='a')
except IOError as e:
- GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
- {'filePath': filePath, 'error': e},
+ GError(_("Unable to write file '%(filePath)s'.\n\nDetails: %(error)s") %
+ {'filePath': filePath, 'error': e},
parent=self._guiparent)
return
-
+
try:
fileHistory.write(command + os.linesep)
finally:
fileHistory.close()
-
+
# update wxGUI prompt
if self._giface:
self._giface.UpdateCmdHistory(command)
-
Modified: grass/trunk/gui/wxpython/core/giface.py
===================================================================
--- grass/trunk/gui/wxpython/core/giface.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/giface.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,7 +23,7 @@
from grass.pydispatch.signal import Signal
# to disable Abstract class not referenced
-#pylint: disable=R0921
+# pylint: disable=R0921
class Notification:
@@ -51,6 +51,7 @@
class LayerList(object):
+
def GetSelectedLayers(self, checkedOnly=True):
"""Returns list of selected layers.
@@ -116,6 +117,7 @@
The GrassInterface process is not finished.
"""
+
def RunCmd(self, *args, **kwargs):
"""Executes a command.
"""
@@ -131,7 +133,8 @@
"""
raise NotImplementedError()
- def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+ def WriteCmdLog(self, text, pid=None,
+ notification=Notification.MAKE_VISIBLE):
"""Writes message related to start or end of the command.
"""
raise NotImplementedError()
@@ -202,6 +205,7 @@
class StandaloneGrassInterface():
"""@implements GrassInterface"""
+
def __init__(self):
# Signal when some map is created or updated by a module.
@@ -242,11 +246,18 @@
grass.percent(event.value, 100, 1)
event.Skip()
- def RunCmd(self, command, compReg=True, skipInterface=False,
- onDone=None, onPrepare=None, userData=None, notification=Notification.MAKE_VISIBLE):
- self._gconsole.RunCmd(command=command, compReg=compReg,
- skipInterface=skipInterface, onDone=onDone,
- onPrepare=onPrepare, userData=userData, notification=notification)
+ def RunCmd(
+ self, command, compReg=True, skipInterface=False, onDone=None,
+ onPrepare=None, userData=None,
+ notification=Notification.MAKE_VISIBLE):
+ self._gconsole.RunCmd(
+ command=command,
+ compReg=compReg,
+ skipInterface=skipInterface,
+ onDone=onDone,
+ onPrepare=onPrepare,
+ userData=userData,
+ notification=notification)
def Help(self, entry):
self._gconsole.RunCmd(['g.manual', 'entry=%s' % entry])
@@ -255,7 +266,8 @@
notification=Notification.HIGHLIGHT):
self._write(grass.message, text)
- def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
+ def WriteCmdLog(self, text, pid=None,
+ notification=Notification.MAKE_VISIBLE):
if pid:
text = '(' + str(pid) + ') ' + text
self._write(grass.message, text)
Modified: grass/trunk/gui/wxpython/core/globalvar.py
===================================================================
--- grass/trunk/gui/wxpython/core/globalvar.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/globalvar.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,12 +19,12 @@
sys.exit("GRASS is not running. Exiting...")
# path to python scripts
-ETCDIR = os.path.join(os.getenv("GISBASE"), "etc")
-GUIDIR = os.path.join(os.getenv("GISBASE"), "gui")
+ETCDIR = os.path.join(os.getenv("GISBASE"), "etc")
+GUIDIR = os.path.join(os.getenv("GISBASE"), "gui")
WXGUIDIR = os.path.join(GUIDIR, "wxpython")
-ICONDIR = os.path.join(GUIDIR, "icons")
-IMGDIR = os.path.join(GUIDIR, "images")
-SYMBDIR = os.path.join(IMGDIR, "symbols")
+ICONDIR = os.path.join(GUIDIR, "icons")
+IMGDIR = os.path.join(GUIDIR, "images")
+SYMBDIR = os.path.join(IMGDIR, "symbols")
from core.debug import Debug
@@ -32,7 +32,11 @@
try:
# intended to be used also outside this module
import gettext
- _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+ _ = gettext.translation(
+ 'grasswxpy',
+ os.path.join(
+ os.getenv("GISBASE"),
+ 'locale')).ugettext
except IOError:
# using no translation silently
def null_gettext(string):
@@ -41,6 +45,7 @@
from grass.script.core import get_commands
+
def CheckWxVersion(version):
"""Check wx version"""
ver = wx.__version__
@@ -49,7 +54,8 @@
return True
-def CheckForWx(forceVersion = os.getenv('GRASS_WXVERSION', None)):
+
+def CheckForWx(forceVersion=os.getenv('GRASS_WXVERSION', None)):
"""Try to import wx module and check its version
:param forceVersion: force wxPython version, eg. '2.8'
@@ -70,14 +76,16 @@
version = wx.__version__
if map(int, version.split('.')) < minVersion:
- raise ValueError('Your wxPython version is %s.%s.%s.%s' % tuple(version.split('.')))
+ raise ValueError(
+ 'Your wxPython version is %s.%s.%s.%s' %
+ tuple(version.split('.')))
except ImportError as e:
print >> sys.stderr, 'ERROR: wxGUI requires wxPython. %s' % str(e)
sys.exit(1)
except (ValueError, wxversion.VersionError) as e:
- print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(minVersion) + \
- '%s.' % (str(e))
+ print >> sys.stderr, 'ERROR: wxGUI requires wxPython >= %d.%d.%d.%d. ' % tuple(
+ minVersion) + '%s.' % (str(e))
sys.exit(1)
except locale.Error as e:
print >> sys.stderr, "Unable to set locale:", e
@@ -106,7 +114,7 @@
FN.FNB_NO_NAV_BUTTONS | \
FN.FNB_NO_X_BUTTON
-FNPageColor = wx.Colour(125,200,175)
+FNPageColor = wx.Colour(125, 200, 175)
"""Dialog widget dimension"""
DIALOG_SPIN_SIZE = (150, -1)
@@ -140,7 +148,7 @@
BIN_EXT = SCT_EXT = ''
-def UpdateGRASSAddOnCommands(eList = None):
+def UpdateGRASSAddOnCommands(eList=None):
"""Update list of available GRASS AddOns commands to use when
parsing string from the command line
@@ -155,7 +163,7 @@
addonPath += os.pathsep + os.path.join(addonBase, 'bin')
if sys.platform != 'win32':
addonPath += os.pathsep + os.path.join(addonBase, 'scripts')
-
+
# remove commands first
if eList:
for ext in eList:
@@ -168,15 +176,15 @@
for path in addonPath.split(os.pathsep):
if not os.path.exists(path) or not os.path.isdir(path):
continue
-
+
# check if addon is in the path
if pathList and path not in pathList:
os.environ['PATH'] = path + os.pathsep + os.environ['PATH']
-
+
for fname in os.listdir(path):
if fname in ['docs', 'modules.xml']:
continue
- if grassScripts: # win32
+ if grassScripts: # win32
name, ext = os.path.splitext(fname)
if name not in grassCmd:
if ext not in [BIN_EXT, SCT_EXT]:
@@ -194,7 +202,7 @@
grassCmd.add(fname)
Debug.msg(3, "AddOn commands: %s", fname)
nCmd += 1
-
+
Debug.msg(1, "Number of GRASS AddOn commands: %d", nCmd)
"""@brief Collected GRASS-relared binaries/scripts"""
@@ -210,4 +218,5 @@
wxPython3 = CheckWxVersion([3, 0, 0, 0])
"""@Add GUIDIR/scripts into path"""
-os.environ['PATH'] = os.path.join(GUIDIR, 'scripts') + os.pathsep + os.environ['PATH']
+os.environ['PATH'] = os.path.join(
+ GUIDIR, 'scripts') + os.pathsep + os.environ['PATH']
Modified: grass/trunk/gui/wxpython/core/gthread.py
===================================================================
--- grass/trunk/gui/wxpython/core/gthread.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/gthread.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,6 +23,7 @@
from core.gconsole import EVT_CMD_DONE, wxCmdDone
+
class gThread(threading.Thread, wx.EvtHandler):
"""Thread for various backends"""
requestId = 0
@@ -65,8 +66,8 @@
return gThread.requestId
def GetId(self):
- """Get id for next command"""
- return gThread.requestId + 1
+ """Get id for next command"""
+ return gThread.requestId + 1
def SetId(self, id):
"""Set starting id"""
@@ -95,14 +96,14 @@
if self.terminate:
return
- #except Exception as e:
+ # except Exception as e:
# exception = e;
self.resultQ.put((requestId, ret))
event = wxCmdDone(ondone=vars()['ondone'],
kwds=kwds,
- args=args, #TODO expand args to kwds
+ args=args, # TODO expand args to kwds
ret=ret,
exception=exception,
userdata=vars()['userdata'],
Modified: grass/trunk/gui/wxpython/core/layerlist.py
===================================================================
--- grass/trunk/gui/wxpython/core/layerlist.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/layerlist.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,6 +27,7 @@
a non GUI class (e.g. named LayerTree) which includes this API,
should be used for Layer Manager.
"""
+
def __init__(self):
self._list = []
@@ -179,6 +180,7 @@
...
ValueError: Map <blablabla> not found.
"""
+
def __init__(self):
self._mapType = None
self._name = None
@@ -209,14 +211,20 @@
"""
if not self.hidden:
fullName = name.split('@')
- if len(fullName) == 1 and self._mapType != 'rgb': # skip checking rgb maps for now
+ if len(
+ fullName) == 1 and self._mapType != 'rgb': # skip checking rgb maps for now
if self._mapType is None:
- raise ValueError("To set layer name, the type of layer must be specified.")
+ raise ValueError(
+ "To set layer name, the type of layer must be specified.")
- res = gcore.find_file(name=fullName,
- element=self._internalTypes[self._mapType])
+ res = gcore.find_file(
+ name=fullName,
+ element=self._internalTypes[
+ self._mapType])
if not res['mapset']:
- raise ValueError("Map <{name}> not found.".format(name=name))
+ raise ValueError(
+ "Map <{name}> not found.".format(
+ name=name))
self._name = name + '@' + res['mapset']
else:
self._name = name
@@ -249,7 +257,9 @@
:param mapType: can be 'raster', 'vector', 'raster_3d'
"""
if mapType not in self._mapTypes:
- raise ValueError("Wrong map type used: {mtype}".format(mtype=mapType))
+ raise ValueError(
+ "Wrong map type used: {mtype}".format(
+ mtype=mapType))
self._mapType = mapType
@@ -268,7 +278,9 @@
:param float opacity: value between 0 and 1
"""
if not (0 <= opacity <= 1):
- raise ValueError("Opacity value must be between 0 and 1, not {op}.".format(op=opacity))
+ raise ValueError(
+ "Opacity value must be between 0 and 1, not {op}.".format(
+ op=opacity))
self._opacity = opacity
opacity = property(fget=GetOpacity, fset=SetOpacity)
@@ -302,6 +314,7 @@
class LayerListToRendererConverter:
"""Help class for converting LayerList layers into renderer list (Map)"""
+
def __init__(self, renderer):
"""
Modified: grass/trunk/gui/wxpython/core/menutree.py
===================================================================
--- grass/trunk/gui/wxpython/core/menutree.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/menutree.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -37,9 +37,9 @@
import sys
import copy
try:
- import xml.etree.ElementTree as etree
+ import xml.etree.ElementTree as etree
except ImportError:
- import elementtree.ElementTree as etree # Python <= 2.4
+ import elementtree.ElementTree as etree # Python <= 2.4
import wx
@@ -55,11 +55,12 @@
# TODO: change the system to remove strange derived classes
class MenuTreeModelBuilder:
"""Abstract menu data class"""
+
def __init__(self, filename, expandAddons=True):
- self.menustyle = UserSettings.Get(group = 'appearance',
- key = 'menustyle',
- subkey = 'selection')
+ self.menustyle = UserSettings.Get(group='appearance',
+ key='menustyle',
+ subkey='selection')
xmlTree = etree.parse(filename)
if expandAddons:
@@ -89,14 +90,14 @@
self.model.AppendNode(parent=node, label='', data=data)
elif item.tag == 'menuitem':
origLabel = _(item.find('label').text)
- handler = item.find('handler').text
- desc = item.find('help') # optional
- gcmd = item.find('command') # optional
- keywords = item.find('keywords') # optional
- shortcut = item.find('shortcut') # optional
- wxId = item.find('id') # optional
- icon = item.find('icon') # optional
- if gcmd != None:
+ handler = item.find('handler').text
+ desc = item.find('help') # optional
+ gcmd = item.find('command') # optional
+ keywords = item.find('keywords') # optional
+ shortcut = item.find('shortcut') # optional
+ wxId = item.find('id') # optional
+ icon = item.find('icon') # optional
+ if gcmd is not None:
gcmd = gcmd.text
else:
gcmd = ""
@@ -106,17 +107,17 @@
desc = ""
if keywords is None or keywords.text is None:
keywords = ""
- else:
+ else:
keywords = keywords.text
- if shortcut != None:
+ if shortcut is not None:
shortcut = shortcut.text
else:
shortcut = ""
- if wxId != None:
+ if wxId is not None:
wxId = eval('wx.' + wxId.text)
else:
wxId = wx.ID_ANY
- if icon != None:
+ if icon is not None:
icon = icon.text
else:
icon = ''
@@ -126,8 +127,15 @@
label += ' [' + gcmd + ']'
elif self.menustyle == 2:
label = ' [' + gcmd + ']'
- data = dict(label=origLabel, description=desc, handler=handler,
- command=gcmd, keywords=keywords, shortcut=shortcut, wxId=wxId, icon=icon)
+ data = dict(
+ label=origLabel,
+ description=desc,
+ handler=handler,
+ command=gcmd,
+ keywords=keywords,
+ shortcut=shortcut,
+ wxId=wxId,
+ icon=icon)
self.model.AppendNode(parent=node, label=label, data=data)
elif item.tag == 'menu':
self._createMenu(item, node)
@@ -163,6 +171,7 @@
def PrintCommands(self, fh):
printCommands(self.model.root, fh, itemSep=' | ', menuSep=' > ')
+
def removeSeparators(model, node=None):
if not node:
node = model.root
@@ -172,6 +181,7 @@
else:
model.RemoveNode(node)
+
def printTree(node, fh, indent=0):
if not node.label:
return
@@ -180,6 +190,7 @@
for child in node.children:
printTree(node=child, fh=fh, indent=indent + 2)
+
def printStrings(node, fh):
# node.label - with module in brackets
# node.data['label'] - without module in brackets
@@ -193,6 +204,7 @@
for child in node.children:
printStrings(node=child, fh=fh)
+
def printCommands(node, fh, itemSep, menuSep):
def collectParents(node, parents):
@@ -217,21 +229,22 @@
if __name__ == "__main__":
action = 'strings'
- menu = 'manager'
+ menu = 'manager'
for arg in sys.argv:
if arg in ('strings', 'tree', 'commands', 'dump'):
- action = arg
+ action = arg
elif arg in ('manager', 'module_tree', 'modeler', 'psmap'):
menu = arg
# FIXME: cross-dependencies
if menu == 'manager':
- from lmgr.menudata import LayerManagerMenuData
- from core.globalvar import WXGUIDIR
+ from lmgr.menudata import LayerManagerMenuData
+ from core.globalvar import WXGUIDIR
filename = os.path.join(WXGUIDIR, 'xml', 'menudata.xml')
menudata = LayerManagerMenuData(filename)
- # FIXME: since module descriptions are used again we have now the third copy of the same string (one is in modules)
+ # FIXME: since module descriptions are used again we have now the third
+ # copy of the same string (one is in modules)
elif menu == 'module_tree':
from lmgr.menudata import LayerManagerModuleTree
from core.globalvar import WXGUIDIR
Modified: grass/trunk/gui/wxpython/core/render.py
===================================================================
--- grass/trunk/gui/wxpython/core/render.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/render.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -38,14 +38,15 @@
from grass.pydispatch.signal import Signal
from grass.exceptions import CalledModuleError
-from core import utils
+from core import utils
from core.utils import _
-from core.ws import RenderWMSMgr
-from core.gcmd import GException, GError, RunCommand
-from core.debug import Debug
+from core.ws import RenderWMSMgr
+from core.gcmd import GException, GError, RunCommand
+from core.debug import Debug
from core.settings import UserSettings
from core.gthread import gThread
+
class Layer(object):
"""Virtual class which stores information about layers (map layers and
overlays) of the map composition.
@@ -53,8 +54,9 @@
- For map layer use MapLayer class.
- For overlays use Overlay class.
"""
- def __init__(self, ltype, cmd, Map, name=None,
- active=True, hidden=False, opacity=1.0, mapfile=None, render=True):
+
+ def __init__(self, ltype, cmd, Map, name=None, active=True,
+ hidden=False, opacity=1.0, mapfile=None, render=True):
"""Create new instance
.. todo::
@@ -79,15 +81,17 @@
else:
tempfile_sfx = ".ppm"
- mapfile = tempfile.NamedTemporaryFile(suffix=tempfile_sfx, delete=False)
+ mapfile = tempfile.NamedTemporaryFile(
+ suffix=tempfile_sfx, delete=False)
# we don't want it open, we just need the name
self.mapfile = mapfile.name
mapfile.close()
- os.remove(self.mapfile) # remove empty file
-
- self.maskfile = self.mapfile.rsplit(".",1)[0] + ".pgm"
-
- # stores class which manages rendering instead of simple command - e.g. WMS
+ os.remove(self.mapfile) # remove empty file
+
+ self.maskfile = self.mapfile.rsplit(".", 1)[0] + ".pgm"
+
+ # stores class which manages rendering instead of simple command - e.g.
+ # WMS
self.renderMgr = None
self.Map = Map
@@ -102,27 +106,27 @@
else:
self.cmd = cmdlist_to_tuple(cmd)
- self.active = active
- self.hidden = hidden
+ self.active = active
+ self.hidden = hidden
self.opacity = opacity
self.forceRender = render
- Debug.msg (3, "Layer.__init__(): type=%s, cmd='%s', name=%s, " \
- "active=%d, opacity=%d, hidden=%d" % \
- (self.type, self.GetCmd(string=True), self.name,
- self.active, self.opacity, self.hidden))
+ Debug.msg(3, "Layer.__init__(): type=%s, cmd='%s', name=%s, "
+ "active=%d, opacity=%d, hidden=%d" %
+ (self.type, self.GetCmd(string=True), self.name,
+ self.active, self.opacity, self.hidden))
def __del__(self):
- Debug.msg (3, "Layer.__del__(): layer=%s, cmd='%s'" %
- (self.name, self.GetCmd(string = True)))
+ Debug.msg(3, "Layer.__del__(): layer=%s, cmd='%s'" %
+ (self.name, self.GetCmd(string=True)))
def __str__(self):
return self.GetCmd(string=True)
def __repr__(self):
return self.__str__()
-
+
def Render(self, env=None):
"""Render layer to image
@@ -136,19 +140,20 @@
if self.type == 'raster_3d':
return None
- Debug.msg (3, "Layer.Render(): type=%s, name=%s, file=%s" % \
- (self.type, self.name, self.mapfile))
+ Debug.msg(3, "Layer.Render(): type=%s, name=%s, file=%s" %
+ (self.type, self.name, self.mapfile))
# prepare command for each layer
layertypes = utils.command2ltype.values() + ['overlay', 'command']
if self.type not in layertypes:
- raise GException(_("<%(name)s>: layer type <%(type)s> is not supported") % \
- {'type' : self.type, 'name' : self.name})
-
+ raise GException(
+ _("<%(name)s>: layer type <%(type)s> is not supported") %
+ {'type': self.type, 'name': self.name})
+
if not env:
env = os.environ.copy()
-
+
# render layers
try:
if self.type == 'command':
@@ -161,19 +166,22 @@
else:
self.renderMgr.Render(self.cmd, env)
except GException:
- sys.stderr.write(_("Command '%s' failed\n") % self.GetCmd(string = True))
+ sys.stderr.write(
+ _("Command '%s' failed\n") %
+ self.GetCmd(
+ string=True))
sys.stderr.write(_("Details: %s\n") % e)
-
+
# clean up after problems
for f in [self.mapfile, self.maskfile]:
if not f:
continue
try_remove(f)
f = None
-
+
return self.mapfile
-
- def GetCmd(self, string = False):
+
+ def GetCmd(self, string=False):
"""Get GRASS command as list of string.
:param string: get command as string if True otherwise as list
@@ -210,7 +218,7 @@
"""
return self.opacity
- def GetName(self, fullyQualified = True):
+ def GetName(self, fullyQualified=True):
"""Get map layer name
:param bool fullyQualified: True to return fully qualified name
@@ -224,11 +232,11 @@
return self.name
else:
if '@' in self.name:
- return { 'name' : self.name.split('@')[0],
- 'mapset' : self.name.split('@')[1] }
+ return {'name': self.name.split('@')[0],
+ 'mapset': self.name.split('@')[1]}
else:
- return { 'name' : self.name,
- 'mapset' : '' }
+ return {'name': self.name,
+ 'mapset': ''}
def IsActive(self):
"""Check if layer is activated for rendering"""
@@ -260,18 +268,18 @@
env['GRASS_RENDER_FILE_READ'] = 'FALSE'
env['GRASS_RENDER_TRANSPARENT'] = 'TRUE'
self.renderMgr = renderMgr(self, env)
-
+
self.type = ltype
def SetName(self, name):
"""Set layer name"""
self.name = name
- def SetActive(self, enable = True):
+ def SetActive(self, enable=True):
"""Active or deactive layer"""
self.active = bool(enable)
- def SetHidden(self, enable = False):
+ def SetHidden(self, enable=False):
"""Hide or show map layer in Layer Manager"""
self.hidden = bool(enable)
@@ -292,7 +300,7 @@
self.cmd.append(cmdlist_to_tuple(c))
else:
self.cmd = cmdlist_to_tuple(cmd)
- Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string = True))
+ Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string=True))
# for re-rendering
self.forceRender = True
@@ -309,12 +317,14 @@
"""Get render manager """
return self.renderMgr
+
class MapLayer(Layer):
+
def __init__(self, *args, **kwargs):
"""Represents map layer in the map canvas
"""
Layer.__init__(self, *args, **kwargs)
-
+
def GetMapset(self):
"""Get mapset of map layer
@@ -329,7 +339,9 @@
except IndexError:
return self.name
+
class Overlay(Layer):
+
def __init__(self, id, *args, **kwargs):
"""Represents overlay displayed in map canvas
@@ -337,42 +349,44 @@
"""
Layer.__init__(self, ltype='overlay', *args, **kwargs)
self.id = id
-
+
+
class RenderLayerMgr(wx.EvtHandler):
+
def __init__(self, layer, env):
"""Render layer into image
:param layer: Layer to be rendered
"""
self.layer = layer
-
+
wx.EvtHandler.__init__(self)
self.thread = gThread()
-
+
self.updateProgress = Signal('RenderLayerMgr.updateProgress')
-
+
self._startTime = None
self._render_env = env
def UpdateRenderEnv(self, env):
self._render_env.update(env)
-
+
def Render(self, cmd, env):
"""Render layer
:param cmd: display command given as tuple
:param env: environmental variables used for rendering
"""
- Debug.msg(1, "RenderLayerMgr.Render(%s): force=%d img=%s" % \
+ Debug.msg(1, "RenderLayerMgr.Render(%s): force=%d img=%s" %
(self.layer, self.layer.forceRender, self.layer.mapfile))
-
+
env_cmd = env.copy()
env_cmd.update(self._render_env)
env_cmd['GRASS_RENDER_FILE'] = self.layer.mapfile
cmd_render = copy.deepcopy(cmd)
- cmd_render[1]['quiet'] = True # be quiet
-
+ cmd_render[1]['quiet'] = True # be quiet
+
self._startTime = time.time()
self.thread.Run(callable=self._render, cmd=cmd_render, env=env_cmd,
ondone=self.OnRenderDone)
@@ -383,39 +397,41 @@
return grass.run_command(cmd[0], env=env, **cmd[1])
except CalledModuleError as e:
return 1
-
+
def Abort(self):
"""Abort rendering process"""
Debug.msg(1, "RenderLayerMgr({}).Abort()".format(self.layer))
self.thread.Terminate()
-
+
# force rendering layer next time
self.layer.forceRender = True
self.thread.Terminate(False)
-
+
def IsDownloading(self):
"""Is downloading
:return: always False
"""
return False
-
+
def OnRenderDone(self, event):
"""Rendering done
Emits updateProcess
"""
- Debug.msg(1, "RenderLayerMgr.OnRenderDone(%s): ret=%d time=%f" % \
- (self.layer, event.ret, time.time() - self._startTime))
+ Debug.msg(1, "RenderLayerMgr.OnRenderDone(%s): ret=%d time=%f" %
+ (self.layer, event.ret, time.time() - self._startTime))
if event.ret != 0:
try:
os.remove(self.layer.mapfile)
except:
pass
-
+
self.updateProgress.emit(layer=self.layer)
-
+
+
class RenderMapMgr(wx.EvtHandler):
+
def __init__(self, Map):
"""Render map layers as image composition
@@ -424,21 +440,21 @@
wx.EvtHandler.__init__(self)
self.Map = Map
-
+
self.updateMap = Signal('RenderMapMgr.updateMap')
self.updateProgress = Signal('RenderMapMgr.updateProgress')
self.renderDone = Signal('RenderMapMgr.renderDone')
self.renderDone.connect(self.OnRenderDone)
-
+
# GRASS environment variable (for rendering)
- self._render_env = {"GRASS_RENDER_BACKGROUNDCOLOR" : "000000",
- "GRASS_RENDER_FILE_COMPRESSION" : "0",
- "GRASS_RENDER_TRUECOLOR" : "TRUE",
- "GRASS_RENDER_TRANSPARENT" : "TRUE" }
-
+ self._render_env = {"GRASS_RENDER_BACKGROUNDCOLOR": "000000",
+ "GRASS_RENDER_FILE_COMPRESSION": "0",
+ "GRASS_RENDER_TRUECOLOR": "TRUE",
+ "GRASS_RENDER_TRANSPARENT": "TRUE"}
+
self._init()
self._rendering = False
-
+
def _init(self, env=None):
"""Init render manager
@@ -448,12 +464,12 @@
self.progressInfo = None
self._env = env
self.layers = []
-
+
# re-render from scratch
if os.path.exists(self.Map.mapfile):
os.remove(self.Map.mapfile)
-
- def _renderLayers(self, env, force = False, overlaysOnly = False):
+
+ def _renderLayers(self, env, force=False, overlaysOnly=False):
"""Render all map layers into files
:param dict env: environmental variables to be used for rendering process
@@ -467,7 +483,7 @@
self.layers += self.Map.GetListOfLayers(active=True,
ltype='raster_3d',
except_ltype=True)
-
+
# reset progress
self.ReportProgress()
@@ -479,11 +495,11 @@
layer.Render(env)
else:
layer.GetRenderMgr().updateProgress.emit(layer=layer)
-
+
Debug.msg(1, "RenderMapMgr.Render(): %d layers to be rendered "
"(force=%d, all active layers -> %d)" % (nlayers, force,
len(self.layers)))
-
+
return nlayers
def GetRenderEnv(self, windres=False):
@@ -495,42 +511,44 @@
env['GRASS_REGION'] = self.Map.SetRegion(windres)
env['GRASS_RENDER_WIDTH'] = str(self.Map.width)
env['GRASS_RENDER_HEIGHT'] = str(self.Map.height)
- if UserSettings.Get(group = 'display', key = 'driver', subkey = 'type') == 'png':
+ if UserSettings.Get(group='display', key='driver',
+ subkey='type') == 'png':
env['GRASS_RENDER_IMMEDIATE'] = 'png'
else:
env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
return env
-
- def Render(self, force = False, windres = False):
+
+ def Render(self, force=False, windres=False):
"""Render map composition
:param bool force: force rendering all map layers in the composition
:param windres: True for region resolution instead for map resolution
"""
if self._rendering:
- Debug.msg(1, "RenderMapMgr().Render(): cancelled (already rendering)")
+ Debug.msg(
+ 1, "RenderMapMgr().Render(): cancelled (already rendering)")
return
-
+
wx.BeginBusyCursor()
self._rendering = True
-
+
env = self.GetRenderEnv(windres)
self._init(env)
if self._renderLayers(env, force, windres) == 0:
self.renderDone.emit()
-
+
def OnRenderDone(self):
"""Rendering process done
Make image composiotion, emits updateMap event.
"""
stopTime = time.time()
-
+
maps = list()
masks = list()
opacities = list()
-
+
for layer in self.layers:
if layer.GetType() == 'overlay':
continue
@@ -539,37 +557,37 @@
maps.append(layer.mapfile)
masks.append(layer.maskfile)
opacities.append(str(layer.opacity))
-
+
# run g.pngcomp to get composite image
- bgcolor = ':'.join(map(str, UserSettings.Get(group = 'display', key = 'bgcolor',
- subkey = 'color')))
+ bgcolor = ':'.join(map(str, UserSettings.Get(
+ group='display', key='bgcolor', subkey='color')))
startCompTime = time.time()
if maps:
ret, msg = RunCommand('g.pnmcomp',
- getErrorMsg = True,
- overwrite = True,
- input = '%s' % ",".join(maps),
- mask = '%s' % ",".join(masks),
- opacity = '%s' % ",".join(opacities),
- bgcolor = bgcolor,
- width = self.Map.width,
- height = self.Map.height,
- output = self.Map.mapfile,
+ getErrorMsg=True,
+ overwrite=True,
+ input='%s' % ",".join(maps),
+ mask='%s' % ",".join(masks),
+ opacity='%s' % ",".join(opacities),
+ bgcolor=bgcolor,
+ width=self.Map.width,
+ height=self.Map.height,
+ output=self.Map.mapfile,
env=self._env)
if ret != 0:
self._rendering = False
if wx.IsBusy():
wx.EndBusyCursor()
raise GException(_("Rendering failed: %s" % msg))
-
+
stop = time.time()
- Debug.msg (1, "RenderMapMgr.OnRenderDone() time=%f sec (comp: %f)" % \
- (stop - self._startTime, stop - startCompTime))
-
+ Debug.msg(1, "RenderMapMgr.OnRenderDone() time=%f sec (comp: %f)" %
+ (stop - self._startTime, stop - startCompTime))
+
self._rendering = False
if wx.IsBusy():
wx.EndBusyCursor()
-
+
self.updateMap.emit()
def Abort(self):
@@ -582,20 +600,20 @@
if wx.IsBusy():
wx.EndBusyCursor()
self.updateProgress.emit(range=0, value=0, text=_("Rendering aborted"))
-
+
def ReportProgress(self, layer=None):
"""Calculates progress in rendering/downloading
and emits signal to inform progress bar about progress.
Emits renderDone event when progressVal is equal to range.
-
+
:param layer: Layer to be processed or None to reset
"""
if self.progressInfo is None or layer is None:
- self.progressInfo = {'progresVal' : 0, # current progress value
- 'downloading' : [], # layers, which are downloading data
- 'rendered' : [], # already rendered layers
- 'range' : len(self.layers)}
+ self.progressInfo = {'progresVal': 0, # current progress value
+ 'downloading': [], # layers, which are downloading data
+ 'rendered': [], # already rendered layers
+ 'range': len(self.layers)}
else:
if layer not in self.progressInfo['rendered']:
self.progressInfo['rendered'].append(layer)
@@ -606,7 +624,7 @@
self.progressInfo['progresVal'] += 1
if layer in self.progressInfo['downloading']:
self.progressInfo['downloading'].remove(layer)
-
+
# for updating statusbar text
stText = ''
first = True
@@ -620,44 +638,47 @@
if stText:
stText += '...'
- if self.progressInfo['range'] != len(self.progressInfo['rendered']):
+ if self.progressInfo['range'] != len(self.progressInfo['rendered']):
if stText:
stText = _('Rendering & ') + stText
else:
stText = _('Rendering...')
-
+
self.updateProgress.emit(range=self.progressInfo['range'],
value=self.progressInfo['progresVal'],
text=stText)
-
- if layer and self.progressInfo['progresVal'] == self.progressInfo['range']:
+
+ if layer and self.progressInfo[
+ 'progresVal'] == self.progressInfo['range']:
self.renderDone.emit()
+
class Map(object):
- def __init__(self, gisrc = None):
+
+ def __init__(self, gisrc=None):
"""Map composition (stack of map layers and overlays)
:param gisrc: alternative gisrc (used eg. by georectifier)
"""
- Debug.msg (1, "Map.__init__(): gisrc=%s" % gisrc)
+ Debug.msg(1, "Map.__init__(): gisrc=%s" % gisrc)
# region/extent settigns
- self.wind = dict() # WIND settings (wind file)
- self.region = dict() # region settings (g.region)
- self.width = 640 # map width
- self.height = 480 # map height
+ self.wind = dict() # WIND settings (wind file)
+ self.region = dict() # region settings (g.region)
+ self.width = 640 # map width
+ self.height = 480 # map height
# list of layers
- self.layers = list() # stack of available GRASS layer
+ self.layers = list() # stack of available GRASS layer
- self.overlays = list() # stack of available overlays
- self.ovlookup = dict() # lookup dictionary for overlay items and overlays
+ self.overlays = list() # stack of available overlays
+ self.ovlookup = dict() # lookup dictionary for overlay items and overlays
# path to external gisrc
self.gisrc = gisrc
-
+
# generated file for g.pnmcomp output for rendering the map
- self.mapfile = grass.tempfile(create = False) + '.ppm'
-
+ self.mapfile = grass.tempfile(create=False) + '.ppm'
+
# setting some initial env. variables
if not self.GetWindow():
sys.stderr.write(_("Trying to recover from default region..."))
@@ -669,13 +690,13 @@
self.layerChanged = Signal('Map.layerChanged')
self.layerRemoved = Signal('Map:layerRemoved')
self.layerAdded = Signal('Map:layerAdded')
-
+
self.renderMgr = RenderMapMgr(self)
def GetRenderMgr(self):
"""Get render manager """
return self.renderMgr
-
+
def GetProjInfo(self):
"""Get projection info"""
return self.projinfo
@@ -712,22 +733,26 @@
"""Read WIND file and set up self.wind dictionary"""
# FIXME: duplicated region WIND == g.region (at least some values)
env = grass.gisenv()
- filename = os.path.join (env['GISDBASE'],
- env['LOCATION_NAME'],
- env['MAPSET'],
- "WIND")
+ filename = os.path.join(env['GISDBASE'],
+ env['LOCATION_NAME'],
+ env['MAPSET'],
+ "WIND")
try:
- windfile = open (filename, "r")
+ windfile = open(filename, "r")
except IOError as e:
- sys.exit(_("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % \
- { 'file' : filename, 'ret' : e})
+ sys.exit(
+ _("Error: Unable to open '%(file)s'. Reason: %(ret)s. wxGUI exited.\n") % {
+ 'file': filename,
+ 'ret': e})
for line in windfile.readlines():
line = line.strip()
try:
key, value = line.split(":", 1)
except ValueError as e:
- sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e)
+ sys.stderr.write(
+ _("\nERROR: Unable to read WIND file: %s\n") %
+ e)
return None
self.wind[key.strip()] = value.strip()
@@ -743,16 +768,16 @@
computational resolution. Set computational resolution through
g.region.
"""
- mapwidth = abs(self.region["e"] - self.region["w"])
- mapheight = abs(self.region['n'] - self.region['s'])
+ mapwidth = abs(self.region["e"] - self.region["w"])
+ mapheight = abs(self.region['n'] - self.region['s'])
- self.region["nsres"] = mapheight / self.height
- self.region["ewres"] = mapwidth / self.width
- self.region['rows'] = round(mapheight / self.region["nsres"])
- self.region['cols'] = round(mapwidth / self.region["ewres"])
+ self.region["nsres"] = mapheight / self.height
+ self.region["ewres"] = mapwidth / self.width
+ self.region['rows'] = round(mapheight / self.region["nsres"])
+ self.region['cols'] = round(mapwidth / self.region["ewres"])
self.region['cells'] = self.region['rows'] * self.region['cols']
- Debug.msg (3, "Map.AdjustRegion(): %s" % self.region)
+ Debug.msg(3, "Map.AdjustRegion(): %s" % self.region)
return self.region
@@ -778,8 +803,8 @@
w = float(self.region['w'])
# Calculate rows, columns, and extents
- new['rows'] = math.fabs(round((n-s)/nsres))
- new['cols'] = math.fabs(round((e-w)/ewres))
+ new['rows'] = math.fabs(round((n - s) / nsres))
+ new['cols'] = math.fabs(round((e - w) / ewres))
# Calculate new extents
new['s'] = nsres * round(s / nsres)
@@ -798,9 +823,14 @@
else:
res = self.region["nsres"]
- Debug.msg(3, "Map.AlignExtentFromDisplay(): width=%d, height=%d, res=%f, center=%f,%f" % \
- (self.width, self.height, res, self.region['center_easting'],
- self.region['center_northing']))
+ Debug.msg(
+ 3,
+ "Map.AlignExtentFromDisplay(): width=%d, height=%d, res=%f, center=%f,%f" %
+ (self.width,
+ self.height,
+ res,
+ self.region['center_easting'],
+ self.region['center_northing']))
ew = (self.width / 2) * res
ns = (self.height / 2) * res
@@ -821,21 +851,24 @@
:param size: map size given as tuple
"""
try:
- self.width = int(size[0])
+ self.width = int(size[0])
self.height = int(size[1])
if self.width < 1 or self.height < 1:
- sys.stderr.write(_("Invalid map size %d,%d\n") % (self.width, self.height))
+ sys.stderr.write(
+ _("Invalid map size %d,%d\n") %
+ (self.width, self.height))
raise ValueError
except ValueError:
- self.width = 640
+ self.width = 640
self.height = 480
- Debug.msg(2, "Map.ChangeMapSize(): width=%d, height=%d" % \
- (self.width, self.height))
+ Debug.msg(2, "Map.ChangeMapSize(): width=%d, height=%d" %
+ (self.width, self.height))
- def GetRegion(self, rast=None, zoom=False, vect=None, rast3d=None, regionName=None,
- n=None, s=None, e=None, w=None, default=False,
- update=False, add3d=False):
+ def GetRegion(
+ self, rast=None, zoom=False, vect=None, rast3d=None,
+ regionName=None, n=None, s=None, e=None, w=None, default=False,
+ update=False, add3d=False):
"""Get region settings (g.region -upgc)
Optionally extent, raster or vector map layer can be given.
@@ -896,8 +929,8 @@
cmd['raster_3d'] = rast3d
ret, reg, msg = RunCommand('g.region',
- read = True,
- getErrorMsg = True,
+ read=True,
+ getErrorMsg=True,
env=env,
**cmd)
@@ -912,9 +945,10 @@
message = _("Unable to zoom to 3d raster map <%s>.") % rast3d + \
"\n\n" + _("Details:") + " %s" % msg
else:
- message = _("Unable to get current geographic extent. "
- "Force quiting wxGUI. Please manually run g.region to "
- "fix the problem.")
+ message = _(
+ "Unable to get current geographic extent. "
+ "Force quiting wxGUI. Please manually run g.region to "
+ "fix the problem.")
GError(message)
return self.region
@@ -925,7 +959,7 @@
except ValueError:
region[key] = val
- Debug.msg (3, "Map.GetRegion(): %s" % region)
+ Debug.msg(3, "Map.GetRegion(): %s" % region)
if update:
self.region = region
@@ -939,7 +973,7 @@
"""
return self.region
- def SetRegion(self, windres = False, windres3 = False):
+ def SetRegion(self, windres=False, windres3=False):
"""Render string for GRASS_REGION env. variable, so that the
images will be rendered from desired zoom level.
@@ -952,7 +986,7 @@
grass_region = ""
if windres:
- compRegion = self.GetRegion(add3d = windres3)
+ compRegion = self.GetRegion(add3d=windres3)
region = copy.copy(self.region)
for key in ('nsres', 'ewres', 'cells'):
region[key] = compRegion[key]
@@ -1025,17 +1059,17 @@
grass_region += "depths: %d; " % \
(region['depths'])
else:
- grass_region += key + ": " + self.wind[key] + "; "
+ grass_region += key + ": " + self.wind[key] + "; "
- Debug.msg (3, "Map.SetRegion(): %s" % grass_region)
+ Debug.msg(3, "Map.SetRegion(): %s" % grass_region)
return grass_region
except:
return None
- def GetListOfLayers(self, ltype = None, mapset = None, name = None,
- active = None, hidden = None, except_ltype=False):
+ def GetListOfLayers(self, ltype=None, mapset=None, name=None,
+ active=None, hidden=None, except_ltype=False):
"""Returns list of layers of selected properties or list of
all layers.
@@ -1050,7 +1084,7 @@
"""
selected = []
- if type(ltype) == types.StringType:
+ if isinstance(ltype, types.StringType):
one_type = True
else:
one_type = False
@@ -1063,39 +1097,39 @@
# ["raster", "vector", "wms", ... ]
for layer in llist:
# specified type only
- if ltype != None:
+ if ltype is not None:
if one_type:
if (not except_ltype and layer.type != ltype) or \
- (except_ltype and layer.type == ltype):
+ (except_ltype and layer.type == ltype):
continue
elif not one_type:
if (not except_ltype and layer.type not in ltype) or \
(except_ltype and layer.type in ltype):
continue
-
+
# mapset
- if (mapset != None and ltype != 'overlay') and \
+ if (mapset is not None and ltype != 'overlay') and \
layer.GetMapset() != mapset:
continue
# name
- if name != None and layer.name != name:
+ if name is not None and layer.name != name:
continue
# hidden and active layers
- if active != None and \
- hidden != None:
+ if active is not None and \
+ hidden is not None:
if layer.active == active and \
- layer.hidden == hidden:
+ layer.hidden == hidden:
selected.append(layer)
# active layers
- elif active != None:
+ elif active is not None:
if layer.active == active:
selected.append(layer)
# hidden layers
- elif hidden != None:
+ elif hidden is not None:
if layer.hidden == hidden:
selected.append(layer)
@@ -1103,11 +1137,13 @@
else:
selected.append(layer)
- Debug.msg (3, "Map.GetListOfLayers(ltype=%s): -> %d" % (ltype, len(selected)))
+ Debug.msg(
+ 3, "Map.GetListOfLayers(ltype=%s): -> %d" %
+ (ltype, len(selected)))
return selected
- def Render(self, force = False, windres = False):
+ def Render(self, force=False, windres=False):
"""Creates final image composite
This function can conditionaly use high-level tools, which
@@ -1118,26 +1154,28 @@
resolution
"""
self.renderMgr.Render(force, windres)
-
+
def _addLayer(self, layer, pos=-1):
if layer.type == 'overlay':
llist = self.overlays
else:
llist = self.layers
-
+
# add maplayer to the list of layers
if pos > -1:
llist.insert(pos, layer)
else:
llist.append(layer)
-
- Debug.msg (3, "Map._addLayer(): layer=%s type=%s" % (layer.name, layer.type))
-
+
+ Debug.msg(
+ 3, "Map._addLayer(): layer=%s type=%s" %
+ (layer.name, layer.type))
+
return layer
- def AddLayer(self, ltype, command, name = None,
- active = True, hidden = False, opacity = 1.0, render = False,
- pos = -1):
+ def AddLayer(self, ltype, command, name=None,
+ active=True, hidden=False, opacity=1.0, render=False,
+ pos=-1):
"""Adds generic map layer to list of layers
:param ltype: layer type ('raster', 'vector', etc.)
@@ -1157,24 +1195,27 @@
opacity = 0
elif opacity > 1:
opacity = 1
- layer = MapLayer(ltype = ltype, name = name, cmd = command, Map = self,
- active = active, hidden = hidden, opacity = opacity)
-
+ layer = MapLayer(ltype=ltype, name=name, cmd=command, Map=self,
+ active=active, hidden=hidden, opacity=opacity)
+
self._addLayer(layer, pos)
-
+
renderMgr = layer.GetRenderMgr()
- Debug.msg(1, "Map.AddLayer(): ltype={}, command={}".format(ltype, layer.GetCmd(string=True)))
+ Debug.msg(
+ 1, "Map.AddLayer(): ltype={}, command={}".format(
+ ltype, layer.GetCmd(
+ string=True)))
if renderMgr:
if layer.type == 'wms':
renderMgr.dataFetched.connect(self.renderMgr.ReportProgress)
renderMgr.updateProgress.connect(self.renderMgr.ReportProgress)
layer.forceRender = render
-
+
self.layerAdded.emit(layer=layer)
-
+
return layer
- def DeleteAllLayers(self, overlay = False):
+ def DeleteAllLayers(self, overlay=False):
"""Delete all layers
:param overlay: True to delete also overlayes
@@ -1183,7 +1224,7 @@
if overlay:
self.overlays = []
- def DeleteLayer(self, layer, overlay = False):
+ def DeleteLayer(self, layer, overlay=False):
"""Removes layer from list of layers
:param layer: layer instance in layer tree
@@ -1191,7 +1232,7 @@
:return: removed layer on success or None
"""
- Debug.msg (3, "Map.DeleteLayer(): name=%s" % layer.name)
+ Debug.msg(3, "Map.DeleteLayer(): name=%s" % layer.name)
if overlay:
list = self.overlays
@@ -1219,7 +1260,7 @@
self.layers = layers
Debug.msg(5, "Map.SetLayers(): layers=%s" % (layers))
- def ChangeLayer(self, layer, render = False, **kargs):
+ def ChangeLayer(self, layer, render=False, **kargs):
"""Change map layer properties
:param layer: map layer instance
@@ -1231,10 +1272,10 @@
:param opacity: opacity level range from 0(transparent) - 1(not transparent)
:param render: render an image if True
"""
- Debug.msg (3, "Map.ChangeLayer(): layer=%s" % layer.name)
+ Debug.msg(3, "Map.ChangeLayer(): layer=%s" % layer.name)
if 'ltype' in kargs:
- layer.SetType(kargs['ltype']) # check type
+ layer.SetType(kargs['ltype']) # check type
if 'command' in kargs:
layer.SetCmd(kargs['command'])
@@ -1250,12 +1291,12 @@
if 'opacity' in kargs:
layer.SetOpacity(kargs['opacity'])
-
+
self.forceRender = render
-
+
# not needed since there is self.forceRender
- ### self.layerChanged(layer=layer)
-
+ # self.layerChanged(layer=layer)
+
return layer
def ChangeOpacity(self, layer, opacity):
@@ -1265,12 +1306,14 @@
:param opacity: opacity level <0;1>
"""
# opacity must be <0;1>
- if opacity < 0: opacity = 0
- elif opacity > 1: opacity = 1
+ if opacity < 0:
+ opacity = 0
+ elif opacity > 1:
+ opacity = 1
layer.opacity = opacity
- Debug.msg (3, "Map.ChangeOpacity(): layer=%s, opacity=%f" % \
- (layer.name, layer.opacity))
+ Debug.msg(3, "Map.ChangeOpacity(): layer=%s, opacity=%f" %
+ (layer.name, layer.opacity))
def ChangeLayerActive(self, layer, active):
"""Enable or disable map layer
@@ -1282,20 +1325,20 @@
if active:
layer.forceRender = True
- Debug.msg (3, "Map.ChangeLayerActive(): name='%s' -> active=%d" % \
- (layer.name, layer.active))
+ Debug.msg(3, "Map.ChangeLayerActive(): name='%s' -> active=%d" %
+ (layer.name, layer.active))
- def ChangeLayerName (self, layer, name):
+ def ChangeLayerName(self, layer, name):
"""Change name of the layer
:param layer: layer instance in layer tree
:param name: layer name to set up
"""
- Debug.msg (3, "Map.ChangeLayerName(): from=%s to=%s" % \
- (layer.name, name))
- layer.name = name
+ Debug.msg(3, "Map.ChangeLayerName(): from=%s to=%s" %
+ (layer.name, name))
+ layer.name = name
- def RemoveLayer(self, name = None, id = None):
+ def RemoveLayer(self, name=None, id=None):
"""Removes layer from layer list
Layer is defined by name at mapset or id.
@@ -1319,12 +1362,12 @@
self.layers.remove(layer)
return retlayer
# del by id
- elif id != None:
+ elif id is not None:
return self.layers.pop(id)
return None
- def GetLayerIndex(self, layer, overlay = False):
+ def GetLayerIndex(self, layer, overlay=False):
"""Get index of layer in layer list.
:param layer: layer instace in layer tree
@@ -1344,7 +1387,7 @@
return -1
def AddOverlay(self, id, ltype, command,
- active = True, hidden = True, opacity = 1.0, render = False):
+ active=True, hidden=True, opacity=1.0, render=False):
"""Adds overlay (grid, barscale, legend, etc.) to list of
overlays
@@ -1358,19 +1401,22 @@
:return: new layer on success
:return: None on failure
"""
- overlay = Overlay(id = id, name = ltype, cmd = command, Map = self,
- active = active, hidden = hidden, opacity = opacity)
-
+ overlay = Overlay(id=id, name=ltype, cmd=command, Map=self,
+ active=active, hidden=hidden, opacity=opacity)
+
self._addLayer(overlay)
-
+
renderMgr = overlay.GetRenderMgr()
- Debug.msg (1, "Map.AddOverlay(): cmd={}".format(overlay.GetCmd(string=True)))
+ Debug.msg(
+ 1, "Map.AddOverlay(): cmd={}".format(
+ overlay.GetCmd(
+ string=True)))
if renderMgr:
renderMgr.updateProgress.connect(self.renderMgr.ReportProgress)
overlay.forceRender = render
-
+
return overlay
-
+
def ChangeOverlay(self, id, **kargs):
"""Change overlay properities
@@ -1385,12 +1431,12 @@
:return: new layer on success
"""
- overlay = self.GetOverlay(id, list = False)
- if overlay is None:
- overlay = Overlay(id, ltype = None, cmd = None)
+ overlay = self.GetOverlay(id, list=False)
+ if overlay is None:
+ overlay = Overlay(id, ltype=None, cmd=None)
if 'ltype' in kargs:
- overlay.SetName(kargs['ltype']) # ltype -> overlay
+ overlay.SetName(kargs['ltype']) # ltype -> overlay
if 'command' in kargs:
overlay.SetCmd(kargs['command'])
@@ -1403,10 +1449,10 @@
if 'opacity' in kargs:
overlay.SetOpacity(kargs['opacity'])
-
+
if 'render' in kargs:
overlay.forceRender = kargs['render']
-
+
return overlay
def GetOverlay(self, id, list=False):
@@ -1440,7 +1486,7 @@
:return: removed overlay on success or None
"""
- return self.DeleteLayer(overlay, overlay = True)
+ return self.DeleteLayer(overlay, overlay=True)
def _clean(self, llist):
for layer in llist:
Modified: grass/trunk/gui/wxpython/core/settings.py
===================================================================
--- grass/trunk/gui/wxpython/core/settings.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/settings.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -24,47 +24,52 @@
import copy
import types
-from core import globalvar
-from core.gcmd import GException, GError
+from core import globalvar
+from core.gcmd import GException, GError
from core.utils import GetSettingsPath, PathJoin, rgb2str, _
+
class Settings:
"""Generic class where to store settings"""
+
def __init__(self):
# settings file
self.filePath = os.path.join(GetSettingsPath(), 'wx')
-
+
# key/value separator
self.sep = ';'
-
+
# define default settings
self._defaultSettings() # -> self.defaultSettings
-
+
# read settings from the file
self.userSettings = copy.deepcopy(self.defaultSettings)
try:
self.ReadSettingsFile()
except GException as e:
print >> sys.stderr, e.value
-
+
# define internal settings
- self._internalSettings() # -> self.internalSettings
+ self._internalSettings() # -> self.internalSettings
def _generateLocale(self):
"""Generate locales
"""
try:
- self.locs = os.listdir(os.path.join(os.environ['GISBASE'], 'locale'))
- self.locs.append('en') # GRASS doesn't ship EN po files
+ self.locs = os.listdir(
+ os.path.join(
+ os.environ['GISBASE'],
+ 'locale'))
+ self.locs.append('en') # GRASS doesn't ship EN po files
self.locs.sort()
# Add a default choice to not override system locale
self.locs.insert(0, 'system')
except:
# No NLS
self.locs = ['system']
-
+
return 'system'
-
+
def _defaultSettings(self):
"""Define default settings
"""
@@ -72,761 +77,761 @@
projFile = PathJoin(os.environ["GRASS_PROJSHARE"], 'epsg')
except KeyError:
projFile = ''
-
+
id_loc = self._generateLocale()
-
+
self.defaultSettings = {
#
# general
#
'general': {
# use default window layout (layer manager, displays, ...)
- 'defWindowPos' : {
- 'enabled' : True,
+ 'defWindowPos': {
+ 'enabled': True,
'dim' : '1,1,%d,%d,%d,1,%d,%d' % \
- (globalvar.GM_WINDOW_SIZE[0],
- globalvar.GM_WINDOW_SIZE[1],
- globalvar.GM_WINDOW_SIZE[0] + 1,
- globalvar.MAP_WINDOW_SIZE[0],
- globalvar.MAP_WINDOW_SIZE[1])
- },
+ (globalvar.GM_WINDOW_SIZE[0],
+ globalvar.GM_WINDOW_SIZE[1],
+ globalvar.GM_WINDOW_SIZE[0] + 1,
+ globalvar.MAP_WINDOW_SIZE[0],
+ globalvar.MAP_WINDOW_SIZE[1])
+ },
# workspace
- 'workspace' : {
- 'posDisplay' : {
- 'enabled' : False
- },
- 'posManager' : {
- 'enabled' : False
- },
+ 'workspace': {
+ 'posDisplay': {
+ 'enabled': False
},
+ 'posManager': {
+ 'enabled': False
+ },
},
- 'manager' : {
+ },
+ 'manager': {
# show opacity level widget
- 'changeOpacityLevel' : {
- 'enabled' : False
- },
+ 'changeOpacityLevel': {
+ 'enabled': False
+ },
# ask when removing layer from layer tree
- 'askOnRemoveLayer' : {
- 'enabled' : True
- },
+ 'askOnRemoveLayer': {
+ 'enabled': True
+ },
# ask when quiting wxGUI or closing display
- 'askOnQuit' : {
- 'enabled' : True
- },
+ 'askOnQuit': {
+ 'enabled': True
+ },
# hide tabs
- 'hideTabs' : {
- 'search' : False,
- 'pyshell' : False,
- },
- 'copySelectedTextToClipboard' : {
- 'enabled' : False
- },
+ 'hideTabs': {
+ 'search': False,
+ 'pyshell': False,
},
+ 'copySelectedTextToClipboard': {
+ 'enabled': False
+ },
+ },
#
# appearance
#
'appearance': {
- 'outputfont' : {
- 'type' : 'Courier New',
+ 'outputfont': {
+ 'type': 'Courier New',
'size': '10',
- },
+ },
# expand/collapse element list
- 'elementListExpand' : {
- 'selection' : 0
- },
- 'menustyle' : {
- 'selection' : 1
- },
- 'gSelectPopupHeight' : {
- 'value' : 200
- },
- 'iconTheme' : {
- 'type' : 'grass'
- },
- 'commandNotebook' : {
- 'selection' : 0 if sys.platform in ('win32', 'darwin') else 1
- },
+ 'elementListExpand': {
+ 'selection': 0
},
+ 'menustyle': {
+ 'selection': 1
+ },
+ 'gSelectPopupHeight': {
+ 'value': 200
+ },
+ 'iconTheme': {
+ 'type': 'grass'
+ },
+ 'commandNotebook': {
+ 'selection': 0 if sys.platform in ('win32', 'darwin') else 1
+ },
+ },
#
# language
#
'language': {
'locale': {
- 'lc_all' : id_loc
+ 'lc_all': id_loc
}
},
#
# display
#
'display': {
- 'font' : {
- 'type' : '',
+ 'font': {
+ 'type': '',
'encoding': 'UTF-8',
- },
+ },
'driver': {
'type': 'cairo'
- },
- 'alignExtent' : {
- 'enabled' : True
- },
- 'compResolution' : {
- 'enabled' : False
- },
+ },
+ 'alignExtent': {
+ 'enabled': True
+ },
+ 'compResolution': {
+ 'enabled': False
+ },
'autoRendering': {
- 'enabled' : True
- },
- 'autoZooming' : {
- 'enabled' : False
- },
+ 'enabled': True
+ },
+ 'autoZooming': {
+ 'enabled': False
+ },
'statusbarMode': {
- 'selection' : 0
- },
+ 'selection': 0
+ },
'bgcolor': {
- 'color' : (255, 255, 255, 255),
- },
- 'mouseWheelZoom' : {
- 'selection' : 1,
- },
- 'scrollDirection' : {
- 'selection' : 0,
- },
- 'nvizDepthBuffer' : {
- 'value' : '16',
- },
+ 'color': (255, 255, 255, 255),
},
+ 'mouseWheelZoom': {
+ 'selection': 1,
+ },
+ 'scrollDirection': {
+ 'selection': 0,
+ },
+ 'nvizDepthBuffer': {
+ 'value': '16',
+ },
+ },
#
# projection
#
- 'projection' : {
- 'statusbar' : {
- 'proj4' : '',
- 'epsg' : '',
- 'projFile' : projFile,
- },
- 'format' : {
- 'll' : 'DMS',
- 'precision' : 2,
- },
+ 'projection': {
+ 'statusbar': {
+ 'proj4': '',
+ 'epsg': '',
+ 'projFile': projFile,
},
+ 'format': {
+ 'll': 'DMS',
+ 'precision': 2,
+ },
+ },
#
# Attribute Table Manager
#
- 'atm' : {
- 'highlight' : {
- 'color' : (255, 255, 0, 255),
- 'width' : 2,
- 'auto' : True,
- },
- 'leftDbClick' : {
- 'selection' : 1 # draw selected
- },
- 'askOnDeleteRec' : {
- 'enabled' : True
- },
- 'keycolumn' : {
- 'value' : 'cat'
- },
- 'encoding' : {
- 'value' : '',
- }
+ 'atm': {
+ 'highlight': {
+ 'color': (255, 255, 0, 255),
+ 'width': 2,
+ 'auto': True,
},
+ 'leftDbClick': {
+ 'selection': 1 # draw selected
+ },
+ 'askOnDeleteRec': {
+ 'enabled': True
+ },
+ 'keycolumn': {
+ 'value': 'cat'
+ },
+ 'encoding': {
+ 'value': '',
+ }
+ },
#
# Command
#
'cmd': {
- 'overwrite' : {
- 'enabled' : False
- },
- 'closeDlg' : {
- 'enabled' : False
- },
- 'verbosity' : {
- 'selection' : 'grassenv'
- },
- 'addNewLayer' : {
- 'enabled' : True,
- },
- 'interactiveInput' : {
- 'enabled' : True,
- },
+ 'overwrite': {
+ 'enabled': False
},
+ 'closeDlg': {
+ 'enabled': False
+ },
+ 'verbosity': {
+ 'selection': 'grassenv'
+ },
+ 'addNewLayer': {
+ 'enabled': True,
+ },
+ 'interactiveInput': {
+ 'enabled': True,
+ },
+ },
#
# d.rast
#
'rasterLayer': {
'opaque': {
- 'enabled' : False
- },
+ 'enabled': False
+ },
'colorTable': {
- 'enabled' : False,
- 'selection' : 'rainbow'
- },
+ 'enabled': False,
+ 'selection': 'rainbow'
},
+ },
#
# d.vect
#
'vectorLayer': {
'featureColor': {
- 'color' : (0, 0, 0),
- 'transparent' : {
+ 'color': (0, 0, 0),
+ 'transparent': {
'enabled': False
- }
- },
+ }
+ },
'areaFillColor': {
- 'color' : (200, 200, 200),
- 'transparent' : {
+ 'color': (200, 200, 200),
+ 'transparent': {
'enabled': False
- }
- },
+ }
+ },
'line': {
- 'width' : 0,
- },
+ 'width': 0,
+ },
'point': {
'symbol': 'basic/x',
- 'size' : 5,
- },
+ 'size': 5,
+ },
'showType': {
- 'point' : {
- 'enabled' : True
- },
- 'line' : {
- 'enabled' : True
- },
- 'centroid' : {
- 'enabled' : False
- },
- 'boundary' : {
- 'enabled' : False
- },
- 'area' : {
- 'enabled' : True
- },
- 'face' : {
- 'enabled' : True
- },
+ 'point': {
+ 'enabled': True
},
+ 'line': {
+ 'enabled': True
+ },
+ 'centroid': {
+ 'enabled': False
+ },
+ 'boundary': {
+ 'enabled': False
+ },
+ 'area': {
+ 'enabled': True
+ },
+ 'face': {
+ 'enabled': True
+ },
},
+ },
#
# vdigit
#
- 'vdigit' : {
+ 'vdigit': {
# symbology
- 'symbol' : {
- 'newSegment' : {
- 'enabled' : None,
- 'color' : (255, 0, 0, 255)
- }, # red
- 'newLine' : {
- 'enabled' : None,
- 'color' : (0, 86, 45, 255)
- }, # dark green
- 'highlight' : {
- 'enabled' : None,
- 'color' : (255, 255, 0, 255)
- }, # yellow
- 'highlightDupl' : {
- 'enabled' : None,
- 'color' : (255, 72, 0, 255)
- }, # red
- 'point' : {
- 'enabled' : True,
- 'color' : (0, 0, 0, 255)
- }, # black
- 'line' : {
- 'enabled' : True,
- 'color' : (0, 0, 0, 255)
- }, # black
- 'boundaryNo' : {
- 'enabled' : True,
- 'color' : (126, 126, 126, 255)
- }, # grey
- 'boundaryOne' : {
- 'enabled' : True,
- 'color' : (0, 255, 0, 255)
- }, # green
- 'boundaryTwo' : {
- 'enabled' : True,
- 'color' : (255, 135, 0, 255)
- }, # orange
- 'centroidIn' : {
- 'enabled' : True,
- 'color' : (0, 0, 255, 255)
- }, # blue
- 'centroidOut' : {
- 'enabled' : True,
- 'color' : (165, 42, 42, 255)
- }, # brown
- 'centroidDup' : {
- 'enabled' : True,
- 'color' : (156, 62, 206, 255)
- }, # violet
- 'nodeOne' : {
- 'enabled' : True,
- 'color' : (255, 0, 0, 255)
- }, # red
- 'nodeTwo' : {
- 'enabled' : True,
- 'color' : (0, 86, 45, 255)
- }, # dark green
- 'vertex' : {
- 'enabled' : False,
- 'color' : (255, 20, 147, 255)
- }, # deep pink
- 'area' : {
- 'enabled' : True,
- 'color' : (217, 255, 217, 255)
- }, # green
- 'direction' : {
- 'enabled' : False,
- 'color' : (255, 0, 0, 255)
- }, # red
- },
+ 'symbol': {
+ 'newSegment': {
+ 'enabled': None,
+ 'color': (255, 0, 0, 255)
+ }, # red
+ 'newLine': {
+ 'enabled': None,
+ 'color': (0, 86, 45, 255)
+ }, # dark green
+ 'highlight': {
+ 'enabled': None,
+ 'color': (255, 255, 0, 255)
+ }, # yellow
+ 'highlightDupl': {
+ 'enabled': None,
+ 'color': (255, 72, 0, 255)
+ }, # red
+ 'point': {
+ 'enabled': True,
+ 'color': (0, 0, 0, 255)
+ }, # black
+ 'line': {
+ 'enabled': True,
+ 'color': (0, 0, 0, 255)
+ }, # black
+ 'boundaryNo': {
+ 'enabled': True,
+ 'color': (126, 126, 126, 255)
+ }, # grey
+ 'boundaryOne': {
+ 'enabled': True,
+ 'color': (0, 255, 0, 255)
+ }, # green
+ 'boundaryTwo': {
+ 'enabled': True,
+ 'color': (255, 135, 0, 255)
+ }, # orange
+ 'centroidIn': {
+ 'enabled': True,
+ 'color': (0, 0, 255, 255)
+ }, # blue
+ 'centroidOut': {
+ 'enabled': True,
+ 'color': (165, 42, 42, 255)
+ }, # brown
+ 'centroidDup': {
+ 'enabled': True,
+ 'color': (156, 62, 206, 255)
+ }, # violet
+ 'nodeOne': {
+ 'enabled': True,
+ 'color': (255, 0, 0, 255)
+ }, # red
+ 'nodeTwo': {
+ 'enabled': True,
+ 'color': (0, 86, 45, 255)
+ }, # dark green
+ 'vertex': {
+ 'enabled': False,
+ 'color': (255, 20, 147, 255)
+ }, # deep pink
+ 'area': {
+ 'enabled': True,
+ 'color': (217, 255, 217, 255)
+ }, # green
+ 'direction': {
+ 'enabled': False,
+ 'color': (255, 0, 0, 255)
+ }, # red
+ },
# display
- 'lineWidth' : {
- 'value' : 2,
- 'units' : 'screen pixels'
- },
+ 'lineWidth': {
+ 'value': 2,
+ 'units': 'screen pixels'
+ },
# snapping
- 'snapping' : {
- 'value' : 10,
- 'units' : 'screen pixels'
- },
- 'snapToVertex' : {
- 'enabled' : True
- },
+ 'snapping': {
+ 'value': 10,
+ 'units': 'screen pixels'
+ },
+ 'snapToVertex': {
+ 'enabled': True
+ },
# digitize new record
- 'addRecord' : {
- 'enabled' : True
- },
- 'layer' :{
- 'value' : 1
- },
- 'category' : {
- 'value' : 1
- },
- 'categoryMode' : {
- 'selection' : 0
- },
+ 'addRecord': {
+ 'enabled': True
+ },
+ 'layer': {
+ 'value': 1
+ },
+ 'category': {
+ 'value': 1
+ },
+ 'categoryMode': {
+ 'selection': 0
+ },
# delete existing feature(s)
- 'delRecord' : {
- 'enabled' : True
- },
+ 'delRecord': {
+ 'enabled': True
+ },
# query tool
- 'query' : {
- 'selection' : 0,
- 'box' : True
- },
- 'queryLength' : {
- 'than-selection' : 0,
- 'thresh' : 0
- },
- 'queryDangle' : {
- 'than-selection' : 0,
- 'thresh' : 0
- },
+ 'query': {
+ 'selection': 0,
+ 'box': True
+ },
+ 'queryLength': {
+ 'than-selection': 0,
+ 'thresh': 0
+ },
+ 'queryDangle': {
+ 'than-selection': 0,
+ 'thresh': 0
+ },
# select feature (point, line, centroid, boundary)
'selectType': {
- 'point' : {
- 'enabled' : True
- },
- 'line' : {
- 'enabled' : True
- },
- 'centroid' : {
- 'enabled' : True
- },
- 'boundary' : {
- 'enabled' : True
- },
+ 'point': {
+ 'enabled': True
},
- 'selectThresh' : {
- 'value' : 10,
- 'units' : 'screen pixels'
+ 'line': {
+ 'enabled': True
},
- 'checkForDupl' : {
- 'enabled' : False
+ 'centroid': {
+ 'enabled': True
},
- 'selectInside' : {
- 'enabled' : False
+ 'boundary': {
+ 'enabled': True
},
+ },
+ 'selectThresh': {
+ 'value': 10,
+ 'units': 'screen pixels'
+ },
+ 'checkForDupl': {
+ 'enabled': False
+ },
+ 'selectInside': {
+ 'enabled': False
+ },
# exit
- 'saveOnExit' : {
- 'enabled' : False,
- },
+ 'saveOnExit': {
+ 'enabled': False,
+ },
# break lines on intersection
- 'breakLines' : {
- 'enabled' : True,
- },
+ 'breakLines': {
+ 'enabled': True,
+ },
# close boundary (snap to the first node)
- 'closeBoundary' : {
- 'enabled' : False,
- }
- },
- #
- # plots for profiles, histograms, and scatterplots
- #
+ 'closeBoundary': {
+ 'enabled': False,
+ }
+ },
+ #
+ # plots for profiles, histograms, and scatterplots
+ #
'profile': {
- 'raster' : {
- 'pcolor' : (0, 0, 255, 255), # line color
- 'pwidth' : 1, # line width
- 'pstyle' : 'solid', # line pen style
- 'datatype' : 'cell', # raster type
- },
- 'font' : {
- 'titleSize' : 12,
- 'axisSize' : 11,
- 'legendSize' : 10,
- },
- 'marker' : {
- 'color' : (0, 0, 0, 255),
- 'fill' : 'transparent',
- 'size' : 2,
- 'type' : 'triangle',
- 'legend' : _('Segment break'),
- },
- 'grid' : {
- 'color' : (200, 200, 200, 255),
- 'enabled' : True,
- },
- 'x-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max': 0, # axis max for custom axis range
- 'log' : False,
- },
- 'y-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max': 0, # axis max for custom axis range
- 'log' : False,
- },
- 'legend' : {
- 'enabled' : True
- },
+ 'raster': {
+ 'pcolor': (0, 0, 255, 255), # line color
+ 'pwidth': 1, # line width
+ 'pstyle': 'solid', # line pen style
+ 'datatype': 'cell', # raster type
},
- 'histogram': {
- 'raster' : {
- 'pcolor' : (0, 0, 255, 255), # line color
- 'pwidth' : 1, # line width
- 'pstyle' : 'solid', # line pen style
- 'datatype' : 'cell', # raster type
- },
- 'font' : {
- 'titleSize' : 12,
- 'axisSize' : 11,
- 'legendSize' : 10,
- },
- 'grid' : {
- 'color' : (200, 200, 200, 255),
- 'enabled' : True,
- },
- 'x-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max' : 0, # axis max for custom axis range
- 'log' : False,
- },
- 'y-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max' : 0, # axis max for custom axis range
- 'log' : False,
- },
- 'legend' : {
- 'enabled' : True
- },
+ 'font': {
+ 'titleSize': 12,
+ 'axisSize': 11,
+ 'legendSize': 10,
},
- 'scatter': {
- 'raster' : {
- 'pcolor' : (0, 0, 255, 255),
- 'pfill' : 'solid',
- 'psize' : 1,
- 'ptype' : 'dot',
+ 'marker': {
+ 'color': (0, 0, 0, 255),
+ 'fill': 'transparent',
+ 'size': 2,
+ 'type': 'triangle',
+ 'legend': _('Segment break'),
+ },
+ 'grid': {
+ 'color': (200, 200, 200, 255),
+ 'enabled': True,
+ },
+ 'x-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'y-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'legend': {
+ 'enabled': True
+ },
+ },
+ 'histogram': {
+ 'raster': {
+ 'pcolor': (0, 0, 255, 255), # line color
+ 'pwidth': 1, # line width
+ 'pstyle': 'solid', # line pen style
+ 'datatype': 'cell', # raster type
+ },
+ 'font': {
+ 'titleSize': 12,
+ 'axisSize': 11,
+ 'legendSize': 10,
+ },
+ 'grid': {
+ 'color': (200, 200, 200, 255),
+ 'enabled': True,
+ },
+ 'x-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'y-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'legend': {
+ 'enabled': True
+ },
+ },
+ 'scatter': {
+ 'raster': {
+ 'pcolor': (0, 0, 255, 255),
+ 'pfill': 'solid',
+ 'psize': 1,
+ 'ptype': 'dot',
# FIXME: this is only a quick fix
# using also names used in a base class for compatibility
# probably used only for initialization
# base should be rewritten to not require this
- 'pwidth' : 1, # required by wxplot/base, maybe useless here
- 'pstyle' : 'dot', # line pen style
- 'plegend' : _('Data point'),
- 0 : {'datatype' : 'CELL'},
- 1 : {'datatype' : 'CELL'},
+ 'pwidth': 1, # required by wxplot/base, maybe useless here
+ 'pstyle': 'dot', # line pen style
+ 'plegend': _('Data point'),
+ 0: {'datatype': 'CELL'},
+ 1: {'datatype': 'CELL'},
+ },
+ 'font': {
+ 'titleSize': 12,
+ 'axisSize': 11,
+ 'legendSize': 10,
+ },
+ 'grid': {
+ 'color': (200, 200, 200, 255),
+ 'enabled': True,
+ },
+ 'x-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'y-axis': {
+ 'type': 'auto', # axis format
+ 'min': 0, # axis min for custom axis range
+ 'max': 0, # axis max for custom axis range
+ 'log': False,
+ },
+ 'legend': {
+ 'enabled': True
+ },
+ },
+ 'gcpman': {
+ 'rms': {
+ 'highestonly': True,
+ 'sdfactor': 1,
+ },
+ 'symbol': {
+ 'color': (0, 0, 255, 255),
+ 'hcolor': (255, 0, 0, 255),
+ 'scolor': (0, 255, 0, 255),
+ 'ucolor': (255, 165, 0, 255),
+ 'unused': True,
+ 'size': 8,
+ 'width': 2,
+ },
+ },
+ 'nviz': {
+ 'view': {
+ 'persp': {
+ 'value': 20,
+ 'step': 2,
},
- 'font' : {
- 'titleSize' : 12,
- 'axisSize' : 11,
- 'legendSize' : 10,
+ 'position': {
+ 'x': 0.84,
+ 'y': 0.16,
},
- 'grid' : {
- 'color' : (200, 200, 200, 255),
- 'enabled' : True,
+ 'twist': {
+ 'value': 0,
},
- 'x-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max' : 0, # axis max for custom axis range
- 'log' : False,
+ 'z-exag': {
+ 'min': 0,
+ 'max': 10,
+ 'value': 1,
},
- 'y-axis' : {
- 'type' : 'auto', # axis format
- 'min' : 0, # axis min for custom axis range
- 'max' : 0, # axis max for custom axis range
- 'log' : False,
+ 'background': {
+ 'color': (255, 255, 255, 255), # white
},
- 'legend' : {
- 'enabled' : True
- },
},
- 'gcpman' : {
- 'rms' : {
- 'highestonly' : True,
- 'sdfactor' : 1,
- },
- 'symbol' : {
- 'color' : (0, 0, 255, 255),
- 'hcolor' : (255, 0, 0, 255),
- 'scolor' : (0, 255, 0, 255),
- 'ucolor' : (255, 165, 0, 255),
- 'unused' : True,
- 'size' : 8,
- 'width' : 2,
- },
+ 'fly': {
+ 'exag': {
+ 'move': 5,
+ 'turn': 5,
+ }
},
- 'nviz' : {
- 'view' : {
- 'persp' : {
- 'value' : 20,
- 'step' : 2,
- },
- 'position' : {
- 'x' : 0.84,
- 'y' : 0.16,
- },
- 'twist' : {
- 'value' : 0,
- },
- 'z-exag' : {
- 'min' : 0,
- 'max' : 10,
- 'value': 1,
- },
- 'background' : {
- 'color' : (255, 255, 255, 255), # white
- },
+ 'animation': {
+ 'fps': 24,
+ 'prefix': _("animation")
+ },
+ 'surface': {
+ 'shine': {
+ 'map': False,
+ 'value': 60.0,
},
- 'fly' : {
- 'exag' : {
- 'move' : 5,
- 'turn' : 5,
- }
+ 'color': {
+ 'map': True,
+ 'value': (100, 100, 100, 255), # constant: grey
},
- 'animation' : {
- 'fps' : 24,
- 'prefix' : _("animation")
+ 'draw': {
+ 'wire-color': (136, 136, 136, 255),
+ 'mode': 1, # fine
+ 'style': 1, # surface
+ 'shading': 1, # gouraud
+ 'res-fine': 6,
+ 'res-coarse': 9,
},
- 'surface' : {
- 'shine': {
- 'map' : False,
- 'value' : 60.0,
- },
- 'color' : {
- 'map' : True,
- 'value' : (100, 100, 100, 255), # constant: grey
- },
- 'draw' : {
- 'wire-color' : (136, 136, 136, 255),
- 'mode' : 1, # fine
- 'style' : 1, # surface
- 'shading' : 1, # gouraud
- 'res-fine' : 6,
- 'res-coarse' : 9,
- },
- 'position' : {
- 'x' : 0,
- 'y' : 0,
- 'z' : 0,
- },
+ 'position': {
+ 'x': 0,
+ 'y': 0,
+ 'z': 0,
},
- 'constant' : {
- 'color' : (100, 100, 100, 255),
- 'value' : 0.0,
- 'transp' : 0,
+ },
+ 'constant': {
+ 'color': (100, 100, 100, 255),
+ 'value': 0.0,
+ 'transp': 0,
'resolution': 6
},
- 'vector' : {
- 'lines' : {
- 'show' : False,
- 'width' : 2,
- 'color' : (0, 0, 0, 255),
- 'flat' : False,
- 'height' : 0,
+ 'vector': {
+ 'lines': {
+ 'show': False,
+ 'width': 2,
+ 'color': (0, 0, 0, 255),
+ 'flat': False,
+ 'height': 0,
'rgbcolumn': None,
'sizecolumn': None,
- },
- 'points' : {
- 'show' : False,
- 'size' : 100,
- 'width' : 2,
- 'marker' : 2,
- 'color' : (0, 0, 0, 255),
- 'height' : 0,
+ },
+ 'points': {
+ 'show': False,
+ 'size': 100,
+ 'width': 2,
+ 'marker': 2,
+ 'color': (0, 0, 0, 255),
+ 'height': 0,
'rgbcolumn': None,
'sizecolumn': None,
- }
+ }
+ },
+ 'volume': {
+ 'color': {
+ 'map': True,
+ 'value': (100, 100, 100, 255), # constant: grey
},
- 'volume' : {
- 'color' : {
- 'map' : True,
- 'value' : (100, 100, 100, 255), # constant: grey
- },
- 'draw' : {
- 'mode' : 0, # isosurfaces
- 'shading' : 1, # gouraud
- 'resolution' : 3, # polygon resolution
- 'box' : False # draw wire box
- },
+ 'draw': {
+ 'mode': 0, # isosurfaces
+ 'shading': 1, # gouraud
+ 'resolution': 3, # polygon resolution
+ 'box': False # draw wire box
+ },
'shine': {
- 'map' : False,
- 'value' : 60,
- },
+ 'map': False,
+ 'value': 60,
+ },
'topo': {
- 'map' : None,
- 'value' : 0.0
- },
+ 'map': None,
+ 'value': 0.0
+ },
'transp': {
- 'map' : None,
+ 'map': None,
'value': 0
- },
+ },
'mask': {
- 'map' : None,
+ 'map': None,
'value': ''
- },
+ },
'slice_position': {
- 'x1' : 0,
- 'x2' : 1,
- 'y1' : 0,
- 'y2' : 1,
- 'z1' : 0,
- 'z2' : 1,
- 'axis' : 0,
- }
- },
- 'cplane' : {
+ 'x1': 0,
+ 'x2': 1,
+ 'y1': 0,
+ 'y2': 1,
+ 'z1': 0,
+ 'z2': 1,
+ 'axis': 0,
+ }
+ },
+ 'cplane': {
'shading': 4,
- 'rotation':{
- 'rot': 180,
+ 'rotation': {
+ 'rot': 180,
'tilt': 0
- },
- 'position':{
- 'x' : 0,
- 'y' : 0,
- 'z' : 0
- }
+ },
+ 'position': {
+ 'x': 0,
+ 'y': 0,
+ 'z': 0
+ }
},
- 'light' : {
- 'position' : {
- 'x' : 0.68,
- 'y' : -0.68,
- 'z' : 80,
- },
- 'bright' : 80,
- 'color' : (255, 255, 255, 255), # white
- 'ambient' : 20,
+ 'light': {
+ 'position': {
+ 'x': 0.68,
+ 'y': -0.68,
+ 'z': 80,
},
- 'fringe' : {
- 'elev' : 55,
- 'color' : (128, 128, 128, 255), # grey
- },
+ 'bright': 80,
+ 'color': (255, 255, 255, 255), # white
+ 'ambient': 20,
+ },
+ 'fringe': {
+ 'elev': 55,
+ 'color': (128, 128, 128, 255), # grey
+ },
'arrow': {
'color': (0, 0, 0),
- },
+ },
'scalebar': {
'color': (0, 0, 0),
- }
+ }
+ },
+ 'modeler': {
+ 'disabled': {
+ 'color': (211, 211, 211, 255), # light grey
},
- 'modeler' : {
- 'disabled': {
- 'color': (211, 211, 211, 255), # light grey
+ 'action': {
+ 'color': {
+ 'valid': (180, 234, 154, 255), # light green
+ 'invalid': (255, 255, 255, 255), # white
+ 'running': (255, 0, 0, 255), # red
},
- 'action' : {
- 'color' : {
- 'valid' : (180, 234, 154, 255), # light green
- 'invalid' : (255, 255, 255, 255), # white
- 'running' : (255, 0, 0, 255), # red
- },
- 'size' : {
- 'width' : 125,
- 'height' : 50,
- },
+ 'size': {
+ 'width': 125,
+ 'height': 50,
+ },
'width': {
- 'parameterized' : 2,
- 'default' : 1,
- },
+ 'parameterized': 2,
+ 'default': 1,
},
- 'data' : {
+ },
+ 'data': {
'color': {
- 'raster' : (215, 215, 248, 255), # light blue
- 'raster3d' : (215, 248, 215, 255), # light green
- 'vector' : (248, 215, 215, 255), # light red
- 'dbtable' : (255, 253, 194, 255), # light yellow
- },
- 'size' : {
- 'width' : 175,
- 'height' : 50,
- },
+ 'raster': (215, 215, 248, 255), # light blue
+ 'raster3d': (215, 248, 215, 255), # light green
+ 'vector': (248, 215, 215, 255), # light red
+ 'dbtable': (255, 253, 194, 255), # light yellow
},
- 'loop' : {
- 'color' : {
- 'valid' : (234, 226, 154, 255), # dark yellow
- },
- 'size' : {
- 'width' : 175,
- 'height' : 40,
- },
+ 'size': {
+ 'width': 175,
+ 'height': 50,
},
- 'if-else' : {
- 'size' : {
- 'width' : 150,
- 'height' : 40,
- },
+ },
+ 'loop': {
+ 'color': {
+ 'valid': (234, 226, 154, 255), # dark yellow
},
- 'comment' : {
- 'color' : (255, 233, 208, 255), # light yellow
- 'size' : {
- 'width' : 200,
- 'height' : 100,
- },
+ 'size': {
+ 'width': 175,
+ 'height': 40,
},
},
- 'mapswipe' : {
+ 'if-else': {
+ 'size': {
+ 'width': 150,
+ 'height': 40,
+ },
+ },
+ 'comment': {
+ 'color': (255, 233, 208, 255), # light yellow
+ 'size': {
+ 'width': 200,
+ 'height': 100,
+ },
+ },
+ },
+ 'mapswipe': {
'cursor': {
'color': (0, 0, 0, 255),
'size': 12,
'width': 1,
'type': {
'selection': 0,
- }
- },
+ }
},
+ },
'animation': {
'bgcolor': {
'color': (255, 255, 255, 255),
- },
+ },
'nprocs': {
'value': -1,
- },
+ },
'font': {
'bgcolor': (255, 255, 255, 255),
'fgcolor': (0, 0, 0, 255),
- },
+ },
'temporal': {
'format': '%Y-%m-%d %H:%M:%S',
'nodata': {
'enable': False
- },
},
},
- }
+ },
+ }
# quick fix, http://trac.osgeo.org/grass/ticket/1233
# TODO
@@ -849,20 +854,22 @@
_("Collapse all except current"),
_("Collapse all"),
_("Expand all"))
-
- self.internalSettings['language']['locale']['choices'] = tuple(self.locs)
- self.internalSettings['atm']['leftDbClick']['choices'] = (_('Edit selected record'),
- _('Display selected'))
-
+
+ self.internalSettings['language'][
+ 'locale']['choices'] = tuple(self.locs)
+ self.internalSettings['atm']['leftDbClick']['choices'] = (
+ _('Edit selected record'), _('Display selected'))
+
self.internalSettings['cmd']['verbosity']['choices'] = ('grassenv',
'verbose',
'quiet')
-
- self.internalSettings['appearance']['iconTheme']['choices'] = ('grass',)
+
+ self.internalSettings['appearance'][
+ 'iconTheme']['choices'] = ('grass',)
self.internalSettings['appearance']['menustyle']['choices'] = \
- (_("Classic (labels only)"),
- _("Combined (labels and module names)"),
- _("Expert (module names only)"))
+ (_("Classic (labels only)"),
+ _("Combined (labels and module names)"),
+ _("Expert (module names only)"))
self.internalSettings['appearance']['gSelectPopupHeight']['min'] = 50
# there is also maxHeight given to TreeCtrlComboPopup.GetAdjustedSize
self.internalSettings['appearance']['gSelectPopupHeight']['max'] = 1000
@@ -872,13 +879,14 @@
_("Fancy green"),
_("List left"))
- self.internalSettings['display']['driver']['choices'] = ['cairo', 'png']
- self.internalSettings['display']['statusbarMode']['choices'] = None # set during MapFrame init
- self.internalSettings['display']['mouseWheelZoom']['choices'] = (_('Zoom and recenter'),
- _('Zoom to mouse cursor'),
- _('Nothing'))
- self.internalSettings['display']['scrollDirection']['choices'] = (_('Scroll forward to zoom in'),
- _('Scroll back to zoom in'))
+ self.internalSettings['display'][
+ 'driver']['choices'] = ['cairo', 'png']
+ self.internalSettings['display']['statusbarMode'][
+ 'choices'] = None # set during MapFrame init
+ self.internalSettings['display']['mouseWheelZoom']['choices'] = (
+ _('Zoom and recenter'), _('Zoom to mouse cursor'), _('Nothing'))
+ self.internalSettings['display']['scrollDirection']['choices'] = (
+ _('Scroll forward to zoom in'), _('Scroll back to zoom in'))
self.internalSettings['nviz']['view'] = {}
self.internalSettings['nviz']['view']['twist'] = {}
@@ -901,7 +909,7 @@
self.internalSettings['nviz']['view']['dir']['y'] = -1
self.internalSettings['nviz']['view']['dir']['z'] = -1
self.internalSettings['nviz']['view']['dir']['use'] = False
-
+
for decor in ('arrow', 'scalebar'):
self.internalSettings['nviz'][decor] = {}
self.internalSettings['nviz'][decor]['position'] = {}
@@ -922,26 +930,25 @@
self.internalSettings['vdigit']['bgmap']['value'] = ''
self.internalSettings['mapswipe']['cursor']['type'] = {}
- self.internalSettings['mapswipe']['cursor']['type']['choices'] = (_("cross"),
- _("box"),
- _("circle"))
+ self.internalSettings['mapswipe']['cursor']['type'][
+ 'choices'] = (_("cross"), _("box"), _("circle"))
- def ReadSettingsFile(self, settings = None):
+ def ReadSettingsFile(self, settings=None):
"""Reads settings file (mapset, location, gisdbase)"""
if settings is None:
settings = self.userSettings
-
+
self._readFile(self.filePath, settings)
-
+
# set environment variables
- font = self.Get(group = 'display', key = 'font', subkey = 'type')
- enc = self.Get(group = 'display', key = 'font', subkey = 'encoding')
+ font = self.Get(group='display', key='font', subkey='type')
+ enc = self.Get(group='display', key='font', subkey='encoding')
if font:
os.environ["GRASS_FONT"] = font
if enc:
os.environ["GRASS_ENCODING"] = enc
-
- def _readFile(self, filename, settings = None):
+
+ def _readFile(self, filename, settings=None):
"""Read settings from file to dict
:param filename: settings file path
@@ -949,16 +956,18 @@
"""
if settings is None:
settings = self.userSettings
-
+
if not os.path.exists(filename):
return
-
+
try:
fd = open(filename, "r")
except IOError:
- sys.stderr.write(_("Unable to read settings file <%s>\n") % filename)
+ sys.stderr.write(
+ _("Unable to read settings file <%s>\n") %
+ filename)
return
-
+
try:
line = ''
for line in fd.readlines():
@@ -966,7 +975,7 @@
group, key = line.split(self.sep)[0:2]
kv = line.split(self.sep)[2:]
subkeyMaster = None
- if len(kv) % 2 != 0: # multiple (e.g. nviz)
+ if len(kv) % 2 != 0: # multiple (e.g. nviz)
subkeyMaster = kv[0]
del kv[0]
idx = 0
@@ -975,25 +984,25 @@
subkey = [subkeyMaster, kv[idx]]
else:
subkey = kv[idx]
- value = kv[idx+1]
- value = self._parseValue(value, read = True)
+ value = kv[idx + 1]
+ value = self._parseValue(value, read=True)
self.Append(settings, group, key, subkey, value)
idx += 2
except ValueError as e:
- print >> sys.stderr, _("Error: Reading settings from file <%(file)s> failed.\n"
- "\t\tDetails: %(detail)s\n"
- "\t\tLine: '%(line)s'\n") % { 'file' : filename,
- 'detail' : e,
- 'line' : line }
+ print >>sys.stderr, _(
+ "Error: Reading settings from file <%(file)s> failed.\n"
+ "\t\tDetails: %(detail)s\n"
+ "\t\tLine: '%(line)s'\n") % {
+ 'file': filename, 'detail': e, 'line': line}
fd.close()
-
+
fd.close()
-
- def SaveToFile(self, settings = None):
+
+ def SaveToFile(self, settings=None):
"""Save settings to the file"""
if settings is None:
settings = self.userSettings
-
+
dirPath = GetSettingsPath()
if not os.path.exists(dirPath):
try:
@@ -1001,7 +1010,7 @@
except:
GError(_('Unable to create settings directory'))
return
-
+
try:
file = open(self.filePath, "w")
for group in settings.keys():
@@ -1010,50 +1019,63 @@
file.write('%s%s%s%s' % (group, self.sep, key, self.sep))
for idx in range(len(subkeys)):
value = settings[group][key][subkeys[idx]]
- if type(value) == types.DictType:
+ if isinstance(value, types.DictType):
if idx > 0:
- file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
+ file.write(
+ '%s%s%s%s%s' %
+ (os.linesep, group, self.sep, key, self.sep))
file.write('%s%s' % (subkeys[idx], self.sep))
kvalues = settings[group][key][subkeys[idx]].keys()
srange = range(len(kvalues))
for sidx in srange:
- svalue = self._parseValue(settings[group][key][subkeys[idx]][kvalues[sidx]])
+ svalue = self._parseValue(
+ settings[group][key][
+ subkeys[idx]][
+ kvalues[sidx]])
file.write('%s%s%s' % (kvalues[sidx], self.sep,
svalue))
if sidx < len(kvalues) - 1:
file.write('%s' % self.sep)
else:
- if idx > 0 and \
- type(settings[group][key][subkeys[idx - 1]]) == types.DictType:
- file.write('%s%s%s%s%s' % (os.linesep, group, self.sep, key, self.sep))
- value = self._parseValue(settings[group][key][subkeys[idx]])
- file.write('%s%s%s' % (subkeys[idx], self.sep, value))
- if idx < len(subkeys) - 1 and \
- type(settings[group][key][subkeys[idx + 1]]) != types.DictType:
+ if idx > 0 and isinstance(
+ settings[group][key]
+ [subkeys[idx - 1]],
+ types.DictType):
+ file.write(
+ '%s%s%s%s%s' %
+ (os.linesep, group, self.sep, key, self.sep))
+ value = self._parseValue(
+ settings[group][key][subkeys[idx]])
+ file.write(
+ '%s%s%s' %
+ (subkeys[idx], self.sep, value))
+ if idx < len(subkeys) - 1 and not isinstance(
+ settings[group][key][subkeys[idx + 1]],
+ types.DictType):
file.write('%s' % self.sep)
file.write(os.linesep)
except IOError as e:
raise GException(e)
- except StandardError as e:
+ except Exception as e:
raise GException(_('Writing settings to file <%(file)s> failed.'
- '\n\nDetails: %(detail)s') % { 'file' : self.filePath,
- 'detail' : e })
+ '\n\nDetails: %(detail)s') %
+ {'file': self.filePath, 'detail': e})
file.close()
return self.filePath
-
- def _parseValue(self, value, read = False):
+
+ def _parseValue(self, value, read=False):
"""Parse value to be store in settings file"""
- if read: # -> read settings (cast values)
+ if read: # -> read settings (cast values)
if value == 'True':
value = True
elif value == 'False':
value = False
elif value == 'None':
value = None
- elif ':' in value: # -> color
+ elif ':' in value: # -> color
try:
value = tuple(map(int, value.split(':')))
- except ValueError: # -> string
+ except ValueError: # -> string
pass
else:
try:
@@ -1063,12 +1085,12 @@
value = float(value)
except ValueError:
pass
- else: # -> write settings
- if type(value) == type(()): # -> color
+ else: # -> write settings
+ if isinstance(value, type(())): # -> color
value = str(value[0]) + ':' +\
str(value[1]) + ':' + \
str(value[2])
-
+
return value
def Get(self, group, key=None, subkey=None, settings_type='user'):
@@ -1098,15 +1120,15 @@
else:
return settings[group][key]
else:
- if type(subkey) == type(tuple()) or \
- type(subkey) == type(list()):
+ if isinstance(subkey, type(tuple())) or \
+ isinstance(subkey, type(list())):
return settings[group][key][subkey[0]][subkey[1]]
else:
return settings[group][key][subkey]
except KeyError:
- print >> sys.stderr, "Settings: unable to get value '%s:%s:%s'\n" % \
- (group, key, subkey)
+ print >> sys.stderr, "Settings: unable to get value '%s:%s:%s'\n" % (
+ group, key, subkey)
def Set(self, group, value, key=None, subkey=None, settings_type='user'):
"""Set value of key/subkey
@@ -1134,19 +1156,20 @@
else:
settings[group][key] = value
else:
- if type(subkey) == type(tuple()) or \
- type(subkey) == type(list()):
+ if isinstance(subkey, type(tuple())) or \
+ isinstance(subkey, type(list())):
settings[group][key][subkey[0]][subkey[1]] = value
else:
settings[group][key][subkey] = value
except KeyError:
- raise GException("%s '%s:%s:%s'" % (_("Unable to set "), group, key, subkey))
+ raise GException("%s '%s:%s:%s'" %
+ (_("Unable to set "), group, key, subkey))
- def Append(self, dict, group, key, subkey, value, overwrite = True):
+ def Append(self, dict, group, key, subkey, value, overwrite=True):
"""Set value of key/subkey
Create group/key/subkey if not exists
-
+
:param dict: settings dictionary to use
:param group: settings group
:param key: key
@@ -1159,19 +1182,19 @@
if group not in dict:
dict[group] = {}
hasValue = False
-
+
if key not in dict[group]:
dict[group][key] = {}
hasValue = False
-
- if type(subkey) == types.ListType:
+
+ if isinstance(subkey, types.ListType):
# TODO: len(subkey) > 2
if subkey[0] not in dict[group][key]:
dict[group][key][subkey[0]] = {}
hasValue = False
if subkey[1] not in dict[group][key][subkey[0]]:
hasValue = False
-
+
try:
if overwrite or (not overwrite and not hasValue):
dict[group][key][subkey[0]][subkey[1]] = value
@@ -1181,19 +1204,19 @@
else:
if subkey not in dict[group][key]:
hasValue = False
-
+
try:
if overwrite or (not overwrite and not hasValue):
dict[group][key][subkey] = value
except TypeError:
print >> sys.stderr, _("Unable to parse settings '%s'") % value + \
' (' + group + ':' + key + ':' + subkey + ')'
-
+
def GetDefaultSettings(self):
"""Get default user settings"""
return self.defaultSettings
- def Reset(self, key = None):
+ def Reset(self, key=None):
"""Reset to default settings
:param key: key in settings dict (None for all keys)
@@ -1202,28 +1225,57 @@
self.userSettings = copy.deepcopy(self.defaultSettings)
else:
self.userSettings[key] = copy.deepcopy(self.defaultSettings[key])
-
+
UserSettings = Settings()
+
def GetDisplayVectSettings():
settings = list()
- if not UserSettings.Get(group = 'vectorLayer', key = 'featureColor', subkey = ['transparent', 'enabled']):
- featureColor = UserSettings.Get(group = 'vectorLayer', key = 'featureColor', subkey = 'color')
- settings.append('color=%s' % rgb2str.get(featureColor, ':'.join(map(str,featureColor))))
+ if not UserSettings.Get(
+ group='vectorLayer', key='featureColor',
+ subkey=['transparent', 'enabled']):
+ featureColor = UserSettings.Get(
+ group='vectorLayer',
+ key='featureColor',
+ subkey='color')
+ settings.append('color=%s' % rgb2str.get(
+ featureColor, ':'.join(map(str, featureColor))))
else:
settings.append('color=none')
- if not UserSettings.Get(group = 'vectorLayer', key = 'areaFillColor', subkey = ['transparent', 'enabled']):
- fillColor = UserSettings.Get(group = 'vectorLayer', key = 'areaFillColor', subkey = 'color')
- settings.append('fcolor=%s' % rgb2str.get(fillColor, ':'.join(map(str,fillColor))))
+ if not UserSettings.Get(
+ group='vectorLayer', key='areaFillColor',
+ subkey=['transparent', 'enabled']):
+ fillColor = UserSettings.Get(
+ group='vectorLayer',
+ key='areaFillColor',
+ subkey='color')
+ settings.append('fcolor=%s' %
+ rgb2str.get(fillColor, ':'.join(map(str, fillColor))))
else:
settings.append('fcolor=none')
-
- settings.append('width=%s' % UserSettings.Get(group = 'vectorLayer', key = 'line', subkey = 'width'))
- settings.append('icon=%s' % UserSettings.Get(group = 'vectorLayer', key = 'point', subkey = 'symbol'))
- settings.append('size=%s' % UserSettings.Get(group = 'vectorLayer', key = 'point', subkey = 'size'))
+
+ settings.append(
+ 'width=%s' %
+ UserSettings.Get(
+ group='vectorLayer',
+ key='line',
+ subkey='width'))
+ settings.append(
+ 'icon=%s' %
+ UserSettings.Get(
+ group='vectorLayer',
+ key='point',
+ subkey='symbol'))
+ settings.append(
+ 'size=%s' %
+ UserSettings.Get(
+ group='vectorLayer',
+ key='point',
+ subkey='size'))
types = []
for ftype in ['point', 'line', 'boundary', 'centroid', 'area', 'face']:
- if UserSettings.Get(group = 'vectorLayer', key = 'showType', subkey = [ftype, 'enabled']):
+ if UserSettings.Get(group='vectorLayer',
+ key='showType', subkey=[ftype, 'enabled']):
types.append(ftype)
settings.append('type=%s' % ','.join(types))
Modified: grass/trunk/gui/wxpython/core/toolboxes.py
===================================================================
--- grass/trunk/gui/wxpython/core/toolboxes.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/toolboxes.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -44,9 +44,9 @@
# this could be placed to functions
-mainMenuFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
-toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
-wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
+mainMenuFile = os.path.join(WXGUIDIR, 'xml', 'main_menu.xml')
+toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
+wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
@@ -62,15 +62,20 @@
# (these files are always check for existence here)
return ""
+
def _getUserToolboxesFile():
- userToolboxesFile = os.path.join(GetSettingsPath(), 'toolboxes', 'toolboxes.xml')
+ userToolboxesFile = os.path.join(
+ GetSettingsPath(),
+ 'toolboxes', 'toolboxes.xml')
if not os.path.exists(userToolboxesFile):
userToolboxesFile = None
return userToolboxesFile
def _getUserMainMenuFile():
- userMainMenuFile = os.path.join(GetSettingsPath(), 'toolboxes', 'main_menu.xml')
+ userMainMenuFile = os.path.join(
+ GetSettingsPath(),
+ 'toolboxes', 'main_menu.xml')
if not os.path.exists(userMainMenuFile):
userMainMenuFile = None
return userMainMenuFile
@@ -144,7 +149,10 @@
If something goes wrong during building or user doesn't modify menu,
default file (from distribution) is returned.
"""
- _debug(1, "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(**locals()))
+ _debug(
+ 1,
+ "toolboxes.getMenudataFile: {userRootFile}, {newFile}, {fallback}".format(
+ **locals()))
distributionRootFile = os.path.join(WXGUIDIR, 'xml', userRootFile)
userRootFile = os.path.join(GetSettingsPath(), 'toolboxes', userRootFile)
@@ -164,23 +172,29 @@
# remove menu file when there is no main_menu and toolboxes
if not _getUserToolboxesFile() and not userRootFile:
os.remove(menudataFile)
- _debug(2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
+ _debug(
+ 2, "toolboxes.getMenudataFile: no user defined files, menudata deleted")
return fallback
if bool(_getUserToolboxesFile()) != bool(userRootFile):
- # always generate new because we don't know if there has been any change
+ # always generate new because we don't know if there has been
+ # any change
generateNew = True
- _debug(2, "toolboxes.getMenudataFile: only one of the user defined files")
+ _debug(
+ 2, "toolboxes.getMenudataFile: only one of the user defined files")
else:
# if newer files -> generate new
menudataTime = os.path.getmtime(menudataFile)
if _getUserToolboxesFile():
- if os.path.getmtime(_getUserToolboxesFile()) > menudataTime:
- _debug(2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
+ if os.path.getmtime(
+ _getUserToolboxesFile()) > menudataTime:
+ _debug(
+ 2, "toolboxes.getMenudataFile: user toolboxes is newer than menudata")
generateNew = True
if userRootFile:
if os.path.getmtime(userRootFile) > menudataTime:
- _debug(2, "toolboxes.getMenudataFile: user root file is newer than menudata")
+ _debug(
+ 2, "toolboxes.getMenudataFile: user root file is newer than menudata")
generateNew = True
elif _getUserToolboxesFile() or userRootFile:
_debug(2, "toolboxes.getMenudataFile: no menudata")
@@ -196,7 +210,9 @@
# Unfortunately, this is the case can be often: defined
# toolboxes but undefined module tree file.
_debug(2, "toolboxes.getMenudataFile: creating a tree")
- tree = createTree(distributionRootFile=distributionRootFile, userRootFile=userRootFile)
+ tree = createTree(
+ distributionRootFile=distributionRootFile,
+ userRootFile=userRootFile)
except ETREE_EXCEPTIONS:
_warning(_("Unable to parse user toolboxes XML files. "
"Default files will be loaded."))
@@ -209,7 +225,9 @@
fh.close()
return menudataFile
except:
- _debug(2, "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
+ _debug(
+ 2,
+ "toolboxes.getMenudataFile: writing menudata failed, returning fallback file")
return fallback
else:
return menudataFile
@@ -236,10 +254,12 @@
try:
os.mkdir(path)
except OSError as e:
- # we cannot use GError or similar because the gui doesn't start at all
- gcore.warning('%(reason)s\n%(detail)s' %
- ({'reason':_('Unable to create toolboxes directory.'),
- 'detail': str(e)}))
+ # we cannot use GError or similar because the gui doesn't start at
+ # all
+ gcore.warning(
+ '%(reason)s\n%(detail)s' % ({
+ 'reason': _('Unable to create toolboxes directory.'),
+ 'detail': str(e)}))
return False
return True
@@ -422,7 +442,9 @@
idx = items.getchildren().index(subtoolbox)
if has_xpath:
- toolbox = toolboxes.find('.//toolbox[@name="%s"]' % subtoolbox.get('name'))
+ toolbox = toolboxes.find(
+ './/toolbox[@name="%s"]' %
+ subtoolbox.get('name'))
else:
toolbox = None
potentialToolboxes = toolboxes.findall('.//toolbox')
@@ -455,7 +477,9 @@
for n in node.findall('./items/user-toolboxes-list'):
items = node.find('./items')
idx = items.getchildren().index(n)
- el = etree.Element('toolbox', attrib={'name': 'GeneratedUserToolboxesList'})
+ el = etree.Element(
+ 'toolbox', attrib={
+ 'name': 'GeneratedUserToolboxesList'})
items.insert(idx, el)
label = etree.SubElement(el, tag='label')
label.text = _("Custom toolboxes")
@@ -485,14 +509,14 @@
_warning(_("List of addons cannot be obtained"
" because g.extension failed."))
return []
-
+
flist = []
for line in output.splitlines():
if not line.startswith('executables'):
continue
for fexe in line.split('=', 1)[1].split(','):
flist.append(fexe)
-
+
return sorted(flist)
@@ -616,13 +640,15 @@
n.text = _escapeXML(','.join(keywords))
if loadMetadata and not desc:
hasErrors = True
-
+
if hasErrors:
# not translatable until toolboxes compilation on Mac is fixed
# translating causes importing globalvar, where sys.exit is called
- sys.stderr.write("WARNING: Some addons failed when loading. "
- "Please consider to update your addons by running 'g.extension.all -f'.\n")
+ sys.stderr.write(
+ "WARNING: Some addons failed when loading. "
+ "Please consider to update your addons by running 'g.extension.all -f'.\n")
+
def _escapeXML(text):
"""Helper function for correct escaping characters for XML.
@@ -786,10 +812,10 @@
"""Tests the module using test files included in the current
directory and in files from distribution.
"""
- toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
+ toolboxesFile = os.path.join(WXGUIDIR, 'xml', 'toolboxes.xml')
userToolboxesFile = 'data/test_toolboxes_user_toolboxes.xml'
menuFile = 'data/test_toolboxes_menu.xml'
- wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
+ wxguiItemsFile = os.path.join(WXGUIDIR, 'xml', 'wxgui_items.xml')
moduleItemsFile = os.path.join(WXGUIDIR, 'xml', 'module_items.xml')
toolboxes = etree.parse(toolboxesFile)
Modified: grass/trunk/gui/wxpython/core/treemodel.py
===================================================================
--- grass/trunk/gui/wxpython/core/treemodel.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/treemodel.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -19,11 +19,11 @@
class TreeModel(object):
"""Class represents a tree structure with hidden root.
-
+
TreeModel is used together with TreeView class to display results in GUI.
The functionality is not complete, only needed methods are implemented.
If needed, the functionality can be extended.
-
+
>>> tree = TreeModel(DictNode)
>>> root = tree.root
>>> n1 = tree.AppendNode(parent=root, label='node1')
@@ -52,6 +52,7 @@
node21
* xxx : 1
"""
+
def __init__(self, nodeClass):
"""Constructor creates root node.
@@ -66,11 +67,11 @@
def AppendNode(self, parent, label, data=None):
"""Create node and append it to parent node.
-
+
:param parent: parent node of the new node
:param label: node label
:param data: optional node data
-
+
:return: new node
"""
node = self.nodeClass(label=label, data=data)
@@ -84,7 +85,7 @@
parent = parent if parent else self.root
self._searchNodes(node=parent, foundNodes=nodes, **kwargs)
return nodes
-
+
def _searchNodes(self, node, foundNodes, **kwargs):
"""Helper method for searching nodes."""
if node.match(**kwargs):
@@ -101,27 +102,25 @@
if len(index) == 0:
return self.root
return self._getNode(self.root, index)
-
+
def GetIndexOfNode(self, node):
"""Method used for communication between view (VirtualTree) and model."""
index = []
return self._getIndex(node, index)
-
-
+
def _getIndex(self, node, index):
if node.parent:
index.insert(0, node.parent.children.index(node))
return self._getIndex(node.parent, index)
return index
-
-
+
def GetChildrenByIndex(self, index):
"""Method used for communication between view (VirtualTree) and model."""
if len(index) == 0:
return self.root.children
node = self._getNode(self.root, index)
return node.children
-
+
def _getNode(self, node, index):
if len(index) == 1:
return node.children[index[0]]
@@ -152,6 +151,7 @@
class DictNode(object):
"""Node which has data in a form of dictionary."""
+
def __init__(self, label, data=None):
"""Create node.
@@ -160,7 +160,7 @@
"""
self.label = label
- if data == None:
+ if data is None:
self.data = dict()
else:
self.data = data
@@ -175,9 +175,9 @@
text.append(indent * ' ' + self.label)
if self.data:
for key, value in self.data.iteritems():
- text.append("%(indent)s* %(key)s : %(value)s" % {'indent': (indent + 2) * ' ',
- 'key': key,
- 'value': value})
+ text.append(
+ "%(indent)s* %(key)s : %(value)s" %
+ {'indent': (indent + 2) * ' ', 'key': key, 'value': value})
if self.children:
for child in self.children:
@@ -196,6 +196,7 @@
class ModuleNode(DictNode):
"""Node representing module."""
+
def __init__(self, label, data=None):
super(ModuleNode, self).__init__(label=label, data=data)
@@ -206,13 +207,15 @@
return False
if key in ('command', 'keywords', 'description'):
try:
- return len(self.data[key]) and (value in self.data[key] or value == '*')
+ return len(
+ self.data[key]) and(
+ value in self.data[key] or value == '*')
except KeyError:
return False
-
+
return False
-
-
+
+
def main():
import doctest
doctest.testmod()
Modified: grass/trunk/gui/wxpython/core/units.py
===================================================================
--- grass/trunk/gui/wxpython/core/units.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/units.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,42 +29,43 @@
from core.utils import _
+
class BaseUnits:
+
def __init__(self):
self._units = dict()
- self._units['length'] = { 0 : { 'key' : 'mu', 'label' : _('map units') },
- 1 : { 'key' : 'me', 'label' : _('meters') },
- 2 : { 'key' : 'km', 'label' : _('kilometers') },
- 3 : { 'key' : 'mi', 'label' : _('miles') },
- 4 : { 'key' : 'ft', 'label' : _('feet') } }
-
- self._units['area'] = { 0 : { 'key' : 'mu', 'label' : _('sq map units') },
- 1 : { 'key' : 'me', 'label' : _('sq meters') },
- 2 : { 'key' : 'km', 'label' : _('sq kilometers') },
- 3 : { 'key' : 'ar', 'label' : _('acres') },
- 4 : { 'key' : 'ht', 'label' : _('hectares') } }
+ self._units['length'] = {0: {'key': 'mu', 'label': _('map units')},
+ 1: {'key': 'me', 'label': _('meters')},
+ 2: {'key': 'km', 'label': _('kilometers')},
+ 3: {'key': 'mi', 'label': _('miles')},
+ 4: {'key': 'ft', 'label': _('feet')}}
+ self._units['area'] = {0: {'key': 'mu', 'label': _('sq map units')},
+ 1: {'key': 'me', 'label': _('sq meters')},
+ 2: {'key': 'km', 'label': _('sq kilometers')},
+ 3: {'key': 'ar', 'label': _('acres')},
+ 4: {'key': 'ht', 'label': _('hectares')}}
+
def GetUnitsList(self, type):
"""Get list of units (their labels)
-
+
:param type: units type ('length' or 'area')
-
+
:return: list of units labels
"""
result = list()
try:
- keys = self._units[type].keys()
- keys.sort()
+ keys = sorted(self._units[type].keys())
for idx in keys:
result.append(self._units[type][idx]['label'])
except KeyError:
pass
-
+
return result
def GetUnitsKey(self, type, index):
"""Get units key based on index
-
+
:param type: units type ('length' or 'area')
:param index: units index
"""
@@ -72,7 +73,7 @@
def GetUnitsIndex(self, type, key):
"""Get units index based on key
-
+
:param type: units type ('length' or 'area')
:param key: units key, e.g. 'me' for meters
@@ -85,6 +86,7 @@
Units = BaseUnits()
+
def ConvertValue(value, type, units):
"""Convert value from map units to given units
@@ -96,7 +98,7 @@
"""
# get map units
# TODO
-
+
f = 1
if type == 'length':
if units == 'me':
@@ -107,7 +109,7 @@
f = 6.21371192237334e-4
elif units == 'ft':
f = 3.28083989501312
- else: # -> area
+ else: # -> area
if units == 'me':
f = 1.0
elif units == 'km':
@@ -125,80 +127,80 @@
def formatDist(distance, mapunits):
- """Formats length numbers and units in a nice way.
+ """Formats length numbers and units in a nice way.
- Formats length numbers and units as a function of length.
+ Formats length numbers and units as a function of length.
- >>> formatDist(20.56915, 'metres')
- (20.57, 'm')
- >>> formatDist(6983.4591, 'metres')
- (6.983, 'km')
- >>> formatDist(0.59, 'feet')
- (0.59, 'ft')
- >>> formatDist(8562, 'feet')
- (1.622, 'miles')
- >>> formatDist(0.48963, 'degrees')
- (29.38, 'min')
- >>> formatDist(20.2546, 'degrees')
- (20.25, 'deg')
- >>> formatDist(82.146, 'unknown')
- (82.15, 'units')
+ >>> formatDist(20.56915, 'metres')
+ (20.57, 'm')
+ >>> formatDist(6983.4591, 'metres')
+ (6.983, 'km')
+ >>> formatDist(0.59, 'feet')
+ (0.59, 'ft')
+ >>> formatDist(8562, 'feet')
+ (1.622, 'miles')
+ >>> formatDist(0.48963, 'degrees')
+ (29.38, 'min')
+ >>> formatDist(20.2546, 'degrees')
+ (20.25, 'deg')
+ >>> formatDist(82.146, 'unknown')
+ (82.15, 'units')
- Accepted map units are 'meters', 'metres', 'feet', 'degree'.
- Returns 'units' instead of unrecognized units.
+ Accepted map units are 'meters', 'metres', 'feet', 'degree'.
+ Returns 'units' instead of unrecognized units.
- :param distance: map units
- :param mapunits: map units
+ :param distance: map units
+ :param mapunits: map units
- From code by Hamish Bowman Grass Development Team 2006.
- """
- if mapunits == 'metres':
- mapunits = 'meters'
- outunits = mapunits
- distance = float(distance)
- divisor = 1.0
+ From code by Hamish Bowman Grass Development Team 2006.
+ """
+ if mapunits == 'metres':
+ mapunits = 'meters'
+ outunits = mapunits
+ distance = float(distance)
+ divisor = 1.0
- # figure out which units to use
- if mapunits == 'meters':
- if distance > 2500.0:
- outunits = 'km'
- divisor = 1000.0
- else:
- outunits = 'm'
- elif mapunits == 'feet':
- # nano-bug: we match any "feet", but US Survey feet is really
- # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
- # miles the tick markers are rounded to the nearest 10th of a
- # mile (528'), the difference in foot flavours is ignored.
- if distance > 5280.0:
- outunits = 'miles'
- divisor = 5280.0
- else:
- outunits = 'ft'
- elif 'degree' in mapunits:
- # was: 'degree' in mapunits and not haveCtypes (for unknown reason)
- if distance < 1:
- outunits = 'min'
- divisor = (1 / 60.0)
- else:
- outunits = 'deg'
+ # figure out which units to use
+ if mapunits == 'meters':
+ if distance > 2500.0:
+ outunits = 'km'
+ divisor = 1000.0
else:
- return (distance, 'units')
-
- # format numbers in a nice way
- if (distance / divisor) >= 2500.0:
- outdistance = round(distance / divisor)
- elif (distance / divisor) >= 1000.0:
- outdistance = round(distance / divisor, 1)
- elif (distance / divisor) > 0.0:
- outdistance = round(distance / divisor,
- int(math.ceil(3 - math.log10(distance / divisor))))
+ outunits = 'm'
+ elif mapunits == 'feet':
+ # nano-bug: we match any "feet", but US Survey feet is really
+ # 5279.9894 per statute mile, or 10.6' per 1000 miles. As >1000
+ # miles the tick markers are rounded to the nearest 10th of a
+ # mile (528'), the difference in foot flavours is ignored.
+ if distance > 5280.0:
+ outunits = 'miles'
+ divisor = 5280.0
else:
- outdistance = float(distance / divisor)
+ outunits = 'ft'
+ elif 'degree' in mapunits:
+ # was: 'degree' in mapunits and not haveCtypes (for unknown reason)
+ if distance < 1:
+ outunits = 'min'
+ divisor = (1 / 60.0)
+ else:
+ outunits = 'deg'
+ else:
+ return (distance, 'units')
- return (outdistance, outunits)
+ # format numbers in a nice way
+ if (distance / divisor) >= 2500.0:
+ outdistance = round(distance / divisor)
+ elif (distance / divisor) >= 1000.0:
+ outdistance = round(distance / divisor, 1)
+ elif (distance / divisor) > 0.0:
+ outdistance = round(distance / divisor,
+ int(math.ceil(3 - math.log10(distance / divisor))))
+ else:
+ outdistance = float(distance / divisor)
+ return (outdistance, outunits)
+
def doc_test():
"""Tests the module using doctest
Modified: grass/trunk/gui/wxpython/core/utils.py
===================================================================
--- grass/trunk/gui/wxpython/core/utils.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/utils.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,23 +26,29 @@
from grass.exceptions import OpenError
from core import globalvar
-from core.gcmd import RunCommand
+from core.gcmd import RunCommand
from core.debug import Debug
try:
# intended to be used also outside this module
import gettext
- _ = gettext.translation('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale')).ugettext
+ _ = gettext.translation(
+ 'grasswxpy',
+ os.path.join(
+ os.getenv("GISBASE"),
+ 'locale')).ugettext
except IOError:
# using no translation silently
def null_gettext(string):
return string
_ = null_gettext
+
def normalize_whitespace(text):
"""Remove redundant whitespace from a string"""
return string.join(string.split(text), ' ')
+
def split(s):
"""Platform spefic shlex.split"""
try:
@@ -52,9 +58,10 @@
return shlex.split(s)
except ValueError as e:
sys.stderr.write(_("Syntax error: %s") % e)
-
+
return []
+
def GetTempfile(pref=None):
"""Creates GRASS temporary file using defined prefix.
@@ -66,8 +73,8 @@
:return: Path to file name (string) or None
"""
ret = RunCommand('g.tempfile',
- read = True,
- pid = os.getpid())
+ read=True,
+ pid=os.getpid())
tempfile = ret.splitlines()[0].strip()
@@ -84,27 +91,28 @@
except:
return None
-def GetLayerNameFromCmd(dcmd, fullyQualified = False, param = None,
- layerType = None):
+
+def GetLayerNameFromCmd(dcmd, fullyQualified=False, param=None,
+ layerType=None):
"""Get map name from GRASS command
-
+
Parameter dcmd can be modified when first parameter is not
defined.
-
+
:param dcmd: GRASS command (given as list)
:param fullyQualified: change map name to be fully qualified
:param param: params directory
:param str layerType: check also layer type ('raster', 'vector',
'raster_3d', ...)
-
+
:return: tuple (name, found)
"""
mapname = ''
- found = True
-
+ found = True
+
if len(dcmd) < 1:
return mapname, False
-
+
if 'd.grid' == dcmd[0]:
mapname = 'grid'
elif 'd.geodesic' in dcmd[0]:
@@ -120,7 +128,7 @@
p, v = dcmd[idx].split('=', 1)
except ValueError:
continue
-
+
if p == param:
params = [(idx, p, v)]
break
@@ -157,7 +165,8 @@
mapname = v
mapset = ''
if fullyQualified and '@' not in mapname:
- if layerType in ('raster', 'vector', 'raster_3d', 'rgb', 'his'):
+ if layerType in ('raster', 'vector',
+ 'raster_3d', 'rgb', 'his'):
try:
if layerType in ('raster', 'rgb', 'his'):
findType = 'cell'
@@ -165,15 +174,16 @@
findType = 'grid3'
else:
findType = layerType
- mapset = grass.find_file(mapname, element = findType)['mapset']
- except AttributeError: # not found
+ mapset = grass.find_file(
+ mapname, element=findType)['mapset']
+ except AttributeError: # not found
return '', False
if not mapset:
found = False
else:
- mapset = '' # grass.gisenv()['MAPSET']
+ mapset = '' # grass.gisenv()['MAPSET']
mapsets[i] = mapset
-
+
# update dcmd
for i, p, v in params:
if p == 'layer':
@@ -181,7 +191,7 @@
dcmd[i] = p + '=' + v
if i in mapsets and mapsets[i]:
dcmd[i] += '@' + mapsets[i]
-
+
maps = list()
ogr = False
for i, p, v in params:
@@ -190,44 +200,46 @@
if p == 'layer' and not ogr:
continue
maps.append(dcmd[i].split('=', 1)[1])
-
+
mapname = '\n'.join(maps)
-
+
return mapname, found
+
def GetValidLayerName(name):
"""Make layer name SQL compliant, based on G_str_to_sql()
-
+
.. todo::
Better use directly Ctypes to reuse venerable libgis C fns...
"""
retName = name.strip()
-
+
# check if name is fully qualified
if '@' in retName:
retName, mapset = retName.split('@')
else:
mapset = None
-
+
cIdx = 0
retNameList = list(retName)
for c in retNameList:
if not (c >= 'A' and c <= 'Z') and \
- not (c >= 'a' and c <= 'z') and \
- not (c >= '0' and c <= '9'):
+ not (c >= 'a' and c <= 'z') and \
+ not (c >= '0' and c <= '9'):
retNameList[cIdx] = '_'
cIdx += 1
retName = ''.join(retNameList)
-
+
if not (retName[0] >= 'A' and retName[0] <= 'Z') and \
- not (retName[0] >= 'a' and retName[0] <= 'z'):
+ not (retName[0] >= 'a' and retName[0] <= 'z'):
retName = 'x' + retName[1:]
if mapset:
retName = retName + '@' + mapset
-
+
return retName
+
def ListOfCatsToRange(cats):
"""Convert list of category number to range(s)
@@ -263,38 +275,39 @@
else:
catstr += '%d,' % (cats[i])
i += 1
-
+
return catstr.strip(',')
-def ListOfMapsets(get = 'ordered'):
+
+def ListOfMapsets(get='ordered'):
"""Get list of available/accessible mapsets
:param str get: method ('all', 'accessible', 'ordered')
-
+
:return: list of mapsets
:return: None on error
"""
mapsets = []
-
+
if get == 'all' or get == 'ordered':
ret = RunCommand('g.mapsets',
- read = True,
- quiet = True,
- flags = 'l',
- sep = 'newline')
-
+ read=True,
+ quiet=True,
+ flags='l',
+ sep='newline')
+
if ret:
mapsets = ret.splitlines()
ListSortLower(mapsets)
else:
return None
-
+
if get == 'accessible' or get == 'ordered':
ret = RunCommand('g.mapsets',
- read = True,
- quiet = True,
- flags = 'p',
- sep = 'newline')
+ read=True,
+ quiet=True,
+ flags='p',
+ sep='newline')
if ret:
if get == 'accessible':
mapsets = ret.splitlines()
@@ -305,44 +318,52 @@
mapsets = mapsets_accessible + mapsets
else:
return None
-
+
return mapsets
+
def ListSortLower(list):
"""Sort list items (not case-sensitive)"""
list.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
+
def GetVectorNumberOfLayers(vector):
"""Get list of all vector layers"""
layers = list()
if not vector:
return layers
-
- fullname = grass.find_file(name = vector, element = 'vector')['fullname']
+
+ fullname = grass.find_file(name=vector, element='vector')['fullname']
if not fullname:
- Debug.msg(5, "utils.GetVectorNumberOfLayers(): vector map '%s' not found" % vector)
+ Debug.msg(
+ 5,
+ "utils.GetVectorNumberOfLayers(): vector map '%s' not found" %
+ vector)
return layers
-
+
ret, out, msg = RunCommand('v.category',
- getErrorMsg = True,
- read = True,
- input = fullname,
- option = 'layers')
+ getErrorMsg=True,
+ read=True,
+ input=fullname,
+ option='layers')
if ret != 0:
- sys.stderr.write(_("Vector map <%(map)s>: %(msg)s\n") % { 'map' : fullname, 'msg' : msg })
+ sys.stderr.write(
+ _("Vector map <%(map)s>: %(msg)s\n") %
+ {'map': fullname, 'msg': msg})
return layers
else:
Debug.msg(1, "GetVectorNumberOfLayers(): ret %s" % ret)
-
+
for layer in out.splitlines():
layers.append(layer)
-
- Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" % \
- (fullname, ','.join(layers)))
-
+
+ Debug.msg(3, "utils.GetVectorNumberOfLayers(): vector=%s -> %s" %
+ (fullname, ','.join(layers)))
+
return layers
-def Deg2DMS(lon, lat, string = True, hemisphere = True, precision = 3):
+
+def Deg2DMS(lon, lat, string=True, hemisphere=True, precision=3):
"""Convert deg value to dms string
:param lon: longitude (x)
@@ -350,7 +371,7 @@
:param string: True to return string otherwise tuple
:param hemisphere: print hemisphere
:param precision: seconds precision
-
+
:return: DMS string or tuple of values
:return: empty string on error
"""
@@ -387,43 +408,45 @@
flon = abs(flon)
hlon = ''
hlat = ''
-
- slat = __ll_parts(flat, precision = precision)
- slon = __ll_parts(flon, precision = precision)
+ slat = __ll_parts(flat, precision=precision)
+ slon = __ll_parts(flon, precision=precision)
+
if string:
return slon + hlon + '; ' + slat + hlat
-
+
return (slon + hlon, slat + hlat)
+
def DMS2Deg(lon, lat):
"""Convert dms value to deg
:param lon: longitude (x)
:param lat: latitude (y)
-
+
:return: tuple of converted values
:return: ValueError on error
"""
- x = __ll_parts(lon, reverse = True)
- y = __ll_parts(lat, reverse = True)
-
+ x = __ll_parts(lon, reverse=True)
+ y = __ll_parts(lat, reverse=True)
+
return (x, y)
-def __ll_parts(value, reverse = False, precision = 3):
+
+def __ll_parts(value, reverse=False, precision=3):
"""Converts deg to d:m:s string
:param value: value to be converted
:param reverse: True to convert from d:m:s to deg
:param precision: seconds precision (ignored if reverse is True)
-
+
:return: converted value (string/float)
:return: ValueError on error (reverse == True)
"""
if not reverse:
if value == 0.0:
return '%s%.*f' % ('00:00:0', precision, 0.0)
-
+
d = int(int(value))
m = int((value - d) * 60)
s = ((value - d) * 60 - m) * 60
@@ -439,9 +462,9 @@
s = '0%.*f' % (precision, s)
else:
s = '%.*f' % (precision, s)
-
+
return str(d) + ':' + m + ':' + s
- else: # -> reverse
+ else: # -> reverse
try:
d, m, s = value.split(':')
hs = s[-1]
@@ -461,37 +484,40 @@
s = '0.0'
except ValueError:
raise ValueError
-
+
if hs not in ('N', 'S', 'E', 'W'):
raise ValueError
-
+
coef = 1.0
if hs in ('S', 'W'):
coef = -1.0
-
+
fm = int(m) / 60.0
fs = float(s) / (60 * 60)
-
+
return coef * (float(d) + fm + fs)
-
+
+
def GetCmdString(cmd):
"""Get GRASS command as string.
-
+
:param cmd: GRASS command given as tuple
-
+
:return: command string
"""
return ' '.join(gtask.cmdtuple_to_list(cmd))
+
def PathJoin(*args):
"""Check path created by os.path.join"""
path = os.path.join(*args)
if platform.system() == 'Windows' and \
'/' in path:
return path[1].upper() + ':\\' + path[3:].replace('/', '\\')
-
+
return path
+
def ReadEpsgCodes(path):
"""Read EPSG code from the file
@@ -513,7 +539,7 @@
line = line.strip()
if len(line) < 1:
continue
-
+
if line[0] == '#':
descr = line[1:].strip()
elif line[0] == '<':
@@ -522,18 +548,19 @@
code = int(code.replace('<', '').replace('>', ''))
except ValueError as e:
raise OpenError('{}'.format(e))
-
+
if code is not None:
epsgCodeDict[code] = (descr, params)
code = None
-
+
f.close()
- except StandardError as e:
+ except Exception as e:
raise OpenError('{}'.format(e))
-
+
return epsgCodeDict
-def ReprojectCoordinates(coord, projOut, projIn = None, flags = ''):
+
+def ReprojectCoordinates(coord, projOut, projIn=None, flags=''):
"""Reproject coordinates
:param coord: coordinates given as tuple
@@ -543,13 +570,13 @@
:return: reprojected coordinates (returned as tuple)
"""
coors = RunCommand('m.proj',
- flags = flags,
- input = '-',
- proj_in = projIn,
- proj_out = projOut,
- sep = ';',
- stdin = '%f;%f' % (coord[0], coord[1]),
- read = True)
+ flags=flags,
+ input='-',
+ proj_in=projIn,
+ proj_out=projOut,
+ sep=';',
+ stdin='%f;%f' % (coord[0], coord[1]),
+ read=True)
if coors:
coors = coors.split(';')
e = coors[0]
@@ -565,9 +592,10 @@
return (proj, (float(e), float(n)))
except ValueError:
return (None, None)
-
+
return (None, None)
+
def GetListOfLocations(dbase):
"""Get list of GRASS locations in given dbase
@@ -580,18 +608,21 @@
try:
for location in glob.glob(os.path.join(dbase, "*")):
try:
- if os.path.join(location, "PERMANENT") in glob.glob(os.path.join(location, "*")):
+ if os.path.join(
+ location, "PERMANENT") in glob.glob(
+ os.path.join(location, "*")):
listOfLocations.append(os.path.basename(location))
except:
pass
except UnicodeEncodeError as e:
raise e
-
+
ListSortLower(listOfLocations)
-
+
return listOfLocations
-def GetListOfMapsets(dbase, location, selectable = False):
+
+def GetListOfMapsets(dbase, location, selectable=False):
"""Get list of mapsets in given GRASS location
:param dbase: GRASS database path
@@ -601,80 +632,84 @@
:return: list of mapsets - sorted (PERMANENT first)
"""
listOfMapsets = list()
-
+
if selectable:
ret = RunCommand('g.mapset',
- read = True,
- flags = 'l',
- location = location,
- dbase = dbase)
-
+ read=True,
+ flags='l',
+ location=location,
+ dbase=dbase)
+
if not ret:
return listOfMapsets
-
+
for line in ret.rstrip().splitlines():
listOfMapsets += line.split(' ')
else:
for mapset in glob.glob(os.path.join(dbase, location, "*")):
- if os.path.isdir(mapset) and \
- os.path.isfile(os.path.join(dbase, location, mapset, "WIND")):
+ if os.path.isdir(mapset) and os.path.isfile(
+ os.path.join(dbase, location, mapset, "WIND")):
listOfMapsets.append(os.path.basename(mapset))
-
+
ListSortLower(listOfMapsets)
return listOfMapsets
+
def GetColorTables():
"""Get list of color tables"""
ret = RunCommand('r.colors',
- read = True,
- flags = 'l')
+ read=True,
+ flags='l')
if not ret:
return list()
-
+
return ret.splitlines()
+
def _getGDALFormats():
"""Get dictionary of avaialble GDAL drivers"""
try:
ret = grass.read_command('r.in.gdal',
- quiet = True,
- flags = 'f')
+ quiet=True,
+ flags='f')
except:
ret = None
-
- return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
+ return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
+
+
def _getOGRFormats():
"""Get dictionary of avaialble OGR drivers"""
try:
ret = grass.read_command('v.in.ogr',
- quiet = True,
- flags = 'f')
+ quiet=True,
+ flags='f')
except:
ret = None
- return _parseFormats(ret), _parseFormats(ret, writableOnly = True)
+ return _parseFormats(ret), _parseFormats(ret, writableOnly=True)
-def _parseFormats(output, writableOnly = False):
+
+def _parseFormats(output, writableOnly=False):
"""Parse r.in.gdal/v.in.ogr -f output"""
- formats = { 'file' : list(),
- 'database' : list(),
- 'protocol' : list()
- }
-
+ formats = {'file': list(),
+ 'database': list(),
+ 'protocol': list()
+ }
+
if not output:
return formats
-
+
patt = None
if writableOnly:
patt = re.compile('\(rw\+?\)$', re.IGNORECASE)
-
+
for line in output.splitlines():
key, name = map(lambda x: x.strip(), line.strip().rsplit(':', -1))
-
+
if writableOnly and not patt.search(key):
continue
-
+
if name in ('Memory', 'Virtual Raster', 'In Memory Raster'):
continue
if name in ('PostgreSQL', 'SQLite',
@@ -695,103 +730,104 @@
formats['protocol'].append(name)
else:
formats['file'].append(name)
-
+
for items in formats.itervalues():
items.sort()
-
+
return formats
formats = None
-def GetFormats(writableOnly = False):
+
+def GetFormats(writableOnly=False):
"""Get GDAL/OGR formats"""
global formats
if not formats:
gdalAll, gdalWritable = _getGDALFormats()
- ogrAll, ogrWritable = _getOGRFormats()
+ ogrAll, ogrWritable = _getOGRFormats()
formats = {
- 'all' : {
- 'gdal' : gdalAll,
- 'ogr' : ogrAll,
- },
- 'writable' : {
- 'gdal' : gdalWritable,
- 'ogr' : ogrWritable,
- },
- }
-
+ 'all': {
+ 'gdal': gdalAll,
+ 'ogr': ogrAll,
+ },
+ 'writable': {
+ 'gdal': gdalWritable,
+ 'ogr': ogrWritable,
+ },
+ }
+
if writableOnly:
return formats['writable']
-
+
return formats['all']
rasterFormatExtension = {
- 'GeoTIFF' : 'tif',
- 'Erdas Imagine Images (.img)' : 'img',
- 'Ground-based SAR Applications Testbed File Format (.gff)' : 'gff',
- 'Arc/Info Binary Grid' : 'adf',
- 'Portable Network Graphics' : 'png',
- 'JPEG JFIF' : 'jpg',
- 'Japanese DEM (.mem)' : 'mem',
- 'Graphics Interchange Format (.gif)' : 'gif',
- 'X11 PixMap Format' : 'xpm',
- 'MS Windows Device Independent Bitmap' : 'bmp',
- 'SPOT DIMAP' : 'dim',
- 'RadarSat 2 XML Product' : 'xml',
- 'EarthWatch .TIL' : 'til',
- 'ERMapper .ers Labelled' : 'ers',
- 'ERMapper Compressed Wavelets' : 'ecw',
- 'GRIdded Binary (.grb)' : 'grb',
- 'EUMETSAT Archive native (.nat)' : 'nat',
- 'Idrisi Raster A.1' : 'rst',
- 'Golden Software ASCII Grid (.grd)' : 'grd',
- 'Golden Software Binary Grid (.grd)' : 'grd',
- 'Golden Software 7 Binary Grid (.grd)' : 'grd',
- 'R Object Data Store' : 'r',
- 'USGS DOQ (Old Style)' : 'doq',
- 'USGS DOQ (New Style)' : 'doq',
- 'ENVI .hdr Labelled' : 'hdr',
- 'ESRI .hdr Labelled' : 'hdr',
- 'Generic Binary (.hdr Labelled)' : 'hdr',
- 'PCI .aux Labelled' : 'aux',
- 'EOSAT FAST Format' : 'fst',
- 'VTP .bt (Binary Terrain) 1.3 Format' : 'bt',
- 'FARSITE v.4 Landscape File (.lcp)' : 'lcp',
- 'Swedish Grid RIK (.rik)' : 'rik',
- 'USGS Optional ASCII DEM (and CDED)' : 'dem',
- 'Northwood Numeric Grid Format .grd/.tab' : '',
- 'Northwood Classified Grid Format .grc/.tab' : '',
- 'ARC Digitized Raster Graphics' : 'arc',
- 'Magellan topo (.blx)' : 'blx',
- 'SAGA GIS Binary Grid (.sdat)' : 'sdat'
- }
+ 'GeoTIFF': 'tif',
+ 'Erdas Imagine Images (.img)': 'img',
+ 'Ground-based SAR Applications Testbed File Format (.gff)': 'gff',
+ 'Arc/Info Binary Grid': 'adf',
+ 'Portable Network Graphics': 'png',
+ 'JPEG JFIF': 'jpg',
+ 'Japanese DEM (.mem)': 'mem',
+ 'Graphics Interchange Format (.gif)': 'gif',
+ 'X11 PixMap Format': 'xpm',
+ 'MS Windows Device Independent Bitmap': 'bmp',
+ 'SPOT DIMAP': 'dim',
+ 'RadarSat 2 XML Product': 'xml',
+ 'EarthWatch .TIL': 'til',
+ 'ERMapper .ers Labelled': 'ers',
+ 'ERMapper Compressed Wavelets': 'ecw',
+ 'GRIdded Binary (.grb)': 'grb',
+ 'EUMETSAT Archive native (.nat)': 'nat',
+ 'Idrisi Raster A.1': 'rst',
+ 'Golden Software ASCII Grid (.grd)': 'grd',
+ 'Golden Software Binary Grid (.grd)': 'grd',
+ 'Golden Software 7 Binary Grid (.grd)': 'grd',
+ 'R Object Data Store': 'r',
+ 'USGS DOQ (Old Style)': 'doq',
+ 'USGS DOQ (New Style)': 'doq',
+ 'ENVI .hdr Labelled': 'hdr',
+ 'ESRI .hdr Labelled': 'hdr',
+ 'Generic Binary (.hdr Labelled)': 'hdr',
+ 'PCI .aux Labelled': 'aux',
+ 'EOSAT FAST Format': 'fst',
+ 'VTP .bt (Binary Terrain) 1.3 Format': 'bt',
+ 'FARSITE v.4 Landscape File (.lcp)': 'lcp',
+ 'Swedish Grid RIK (.rik)': 'rik',
+ 'USGS Optional ASCII DEM (and CDED)': 'dem',
+ 'Northwood Numeric Grid Format .grd/.tab': '',
+ 'Northwood Classified Grid Format .grc/.tab': '',
+ 'ARC Digitized Raster Graphics': 'arc',
+ 'Magellan topo (.blx)': 'blx',
+ 'SAGA GIS Binary Grid (.sdat)': 'sdat'
+}
vectorFormatExtension = {
- 'ESRI Shapefile' : 'shp',
- 'UK .NTF' : 'ntf',
- 'SDTS' : 'ddf',
- 'DGN' : 'dgn',
- 'VRT' : 'vrt',
- 'REC' : 'rec',
- 'BNA' : 'bna',
- 'CSV' : 'csv',
- 'GML' : 'gml',
- 'GPX' : 'gpx',
- 'KML' : 'kml',
- 'GMT' : 'gmt',
- 'PGeo' : 'mdb',
- 'XPlane' : 'dat',
- 'AVCBin' : 'adf',
- 'AVCE00' : 'e00',
- 'DXF' : 'dxf',
- 'Geoconcept' : 'gxt',
- 'GeoRSS' : 'xml',
- 'GPSTrackMaker' : 'gtm',
- 'VFK' : 'vfk',
- 'SVG' : 'svg',
- }
+ 'ESRI Shapefile': 'shp',
+ 'UK .NTF': 'ntf',
+ 'SDTS': 'ddf',
+ 'DGN': 'dgn',
+ 'VRT': 'vrt',
+ 'REC': 'rec',
+ 'BNA': 'bna',
+ 'CSV': 'csv',
+ 'GML': 'gml',
+ 'GPX': 'gpx',
+ 'KML': 'kml',
+ 'GMT': 'gmt',
+ 'PGeo': 'mdb',
+ 'XPlane': 'dat',
+ 'AVCBin': 'adf',
+ 'AVCE00': 'e00',
+ 'DXF': 'dxf',
+ 'Geoconcept': 'gxt',
+ 'GeoRSS': 'xml',
+ 'GPSTrackMaker': 'gtm',
+ 'VFK': 'vfk',
+ 'SVG': 'svg',
+}
def GetSettingsPath():
@@ -801,22 +837,25 @@
verFd = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
version = int(verFd.readlines()[0].split(' ')[0].split('.')[0])
except (IOError, ValueError, TypeError, IndexError) as e:
- sys.exit(_("ERROR: Unable to determine GRASS version. Details: %s") % e)
-
+ sys.exit(
+ _("ERROR: Unable to determine GRASS version. Details: %s") %
+ e)
+
verFd.close()
# keep location of settings files rc and wx in sync with lib/init/grass.py
if sys.platform == 'win32':
return os.path.join(os.getenv('APPDATA'), 'GRASS%d' % version)
-
+
return os.path.join(os.getenv('HOME'), '.grass%d' % version)
-def StoreEnvVariable(key, value = None, envFile = None):
+
+def StoreEnvVariable(key, value=None, envFile=None):
"""Store environmental variable
If value is not given (is None) then environmental variable is
unset.
-
+
:param key: env key
:param value: env value
:param envFile: path to the environmental file (None for default location)
@@ -825,10 +864,14 @@
if not envFile:
gVersion = grass.version()['version'].split('.', 1)[0]
if not windows:
- envFile = os.path.join(os.getenv('HOME'), '.grass%s' % gVersion, 'bashrc')
+ envFile = os.path.join(
+ os.getenv('HOME'), '.grass%s' %
+ gVersion, 'bashrc')
else:
- envFile = os.path.join(os.getenv('APPDATA'), 'GRASS%s' % gVersion, 'env.bat')
-
+ envFile = os.path.join(
+ os.getenv('APPDATA'), 'GRASS%s' %
+ gVersion, 'env.bat')
+
# read env file
environ = dict()
lineSkipped = list()
@@ -841,8 +884,11 @@
for line in fd.readlines():
line = line.rstrip(os.linesep)
try:
- k, v = map(lambda x: x.strip(), line.split(' ', 1)[1].split('=', 1))
- except StandardError as e:
+ k, v = map(
+ lambda x: x.strip(), line.split(
+ ' ', 1)[1].split(
+ '=', 1))
+ except Exception as e:
sys.stderr.write(_("%s: line skipped - unable to parse '%s'\n"
"Reason: %s\n") % (envFile, line, e))
lineSkipped.append(line)
@@ -850,16 +896,16 @@
if k in environ:
sys.stderr.write(_("Duplicated key: %s\n") % k)
environ[k] = v
-
+
fd.close()
-
+
# update environmental variables
if value is None:
if key in environ:
del environ[key]
else:
environ[key] = value
-
+
# write update env file
try:
fd = open(envFile, 'w')
@@ -870,17 +916,18 @@
expCmd = 'set'
else:
expCmd = 'export'
-
+
for key, value in environ.iteritems():
fd.write('%s %s=%s\n' % (expCmd, key, value))
-
+
# write also skipped lines
for line in lineSkipped:
fd.write(line + os.linesep)
-
+
fd.close()
-def SetAddOnPath(addonPath = None, key = 'PATH'):
+
+def SetAddOnPath(addonPath=None, key='PATH'):
"""Set default AddOn path
:param addonPath: path to addons (None for default)
@@ -897,10 +944,10 @@
addonPath = os.path.join(os.path.join(os.getenv('APPDATA'),
'GRASS%s' % gVersion,
'addons'))
-
- StoreEnvVariable(key = 'GRASS_ADDON_' + key, value = addonPath)
+
+ StoreEnvVariable(key='GRASS_ADDON_' + key, value=addonPath)
os.environ['GRASS_ADDON_' + key] = addonPath
-
+
# update path
if addonPath not in os.environ['PATH']:
os.environ['PATH'] = addonPath + os.pathsep + os.environ['PATH']
@@ -949,32 +996,32 @@
label = _('Select Color')
return (rgb, label)
-command2ltype = {'d.rast' : 'raster',
- 'd.rast3d' : 'raster_3d',
- 'd.rgb' : 'rgb',
- 'd.his' : 'his',
- 'd.shade' : 'shaded',
- 'd.legend' : 'rastleg',
- 'd.rast.arrow' : 'rastarrow',
- 'd.rast.num' : 'rastnum',
- 'd.rast.leg' : 'maplegend',
- 'd.vect' : 'vector',
+command2ltype = {'d.rast': 'raster',
+ 'd.rast3d': 'raster_3d',
+ 'd.rgb': 'rgb',
+ 'd.his': 'his',
+ 'd.shade': 'shaded',
+ 'd.legend': 'rastleg',
+ 'd.rast.arrow': 'rastarrow',
+ 'd.rast.num': 'rastnum',
+ 'd.rast.leg': 'maplegend',
+ 'd.vect': 'vector',
'd.vect.thematic': 'thememap',
- 'd.vect.chart' : 'themechart',
- 'd.grid' : 'grid',
- 'd.geodesic' : 'geodesic',
- 'd.rhumbline' : 'rhumb',
- 'd.labels' : 'labels',
- 'd.barscale' : 'barscale',
- 'd.redraw' : 'redraw',
- 'd.wms' : 'wms',
- 'd.histogram' : 'histogram',
- 'd.colortable' : 'colortable',
- 'd.graph' : 'graph',
- 'd.out.file' : 'export',
- 'd.to.rast' : 'torast',
- 'd.text' : 'text',
- 'd.northarrow' : 'northarrow'
+ 'd.vect.chart': 'themechart',
+ 'd.grid': 'grid',
+ 'd.geodesic': 'geodesic',
+ 'd.rhumbline': 'rhumb',
+ 'd.labels': 'labels',
+ 'd.barscale': 'barscale',
+ 'd.redraw': 'redraw',
+ 'd.wms': 'wms',
+ 'd.histogram': 'histogram',
+ 'd.colortable': 'colortable',
+ 'd.graph': 'graph',
+ 'd.out.file': 'export',
+ 'd.to.rast': 'torast',
+ 'd.text': 'text',
+ 'd.northarrow': 'northarrow'
}
ltype2command = {}
for (cmd, ltype) in command2ltype.items():
@@ -982,24 +1029,24 @@
def GetGEventAttribsForHandler(method, event):
- """Get attributes from event, which can be used by handler method.
+ """Get attributes from event, which can be used by handler method.
Be aware of event class attributes.
:param method: handler method (including self arg)
:param event: event
- :return: (valid kwargs for method,
- list of method's args without default value
+ :return: (valid kwargs for method,
+ list of method's args without default value
which were not found among event attributes)
"""
args_spec = inspect.getargspec(method)
args = args_spec[0]
- defaults =[]
+ defaults = []
if args_spec[3]:
- defaults = args_spec[3]
+ defaults = args_spec[3]
# number of arguments without def value
req_args = len(args) - 1 - len(defaults)
@@ -1016,9 +1063,9 @@
return kwargs, missing_args
-def PilImageToWxImage(pilImage, copyAlpha = True):
+def PilImageToWxImage(pilImage, copyAlpha=True):
"""Convert PIL image to wx.Image
-
+
Based on http://wiki.wxpython.org/WorkingWithImages
"""
import wx
@@ -1027,17 +1074,34 @@
wxImage = wx.EmptyImage(*pilImage.size)
pilImageCopyRGBA = pilImage.copy()
pilImageCopyRGB = pilImageCopyRGBA.convert('RGB') # RGBA --> RGB
- fn = getattr(pilImageCopyRGB, "tobytes", getattr(pilImageCopyRGB, "tostring"))
+ fn = getattr(
+ pilImageCopyRGB,
+ "tobytes",
+ getattr(
+ pilImageCopyRGB,
+ "tostring"))
pilImageRgbData = fn()
wxImage.SetData(pilImageRgbData)
- fn = getattr(pilImageCopyRGBA, "tobytes", getattr(pilImageCopyRGBA, "tostring"))
- wxImage.SetAlphaData(fn()[3::4]) # Create layer and insert alpha values.
+ fn = getattr(
+ pilImageCopyRGBA,
+ "tobytes",
+ getattr(
+ pilImageCopyRGBA,
+ "tostring"))
+ # Create layer and insert alpha values.
+ wxImage.SetAlphaData(fn()[3::4])
else: # The resulting image will not have alpha.
wxImage = wx.EmptyImage(*pilImage.size)
pilImageCopy = pilImage.copy()
- pilImageCopyRGB = pilImageCopy.convert('RGB') # Discard any alpha from the PIL image.
- fn = getattr(pilImageCopyRGB, "tobytes", getattr(pilImageCopyRGB, "tostring"))
+ # Discard any alpha from the PIL image.
+ pilImageCopyRGB = pilImageCopy.convert('RGB')
+ fn = getattr(
+ pilImageCopyRGB,
+ "tobytes",
+ getattr(
+ pilImageCopyRGB,
+ "tostring"))
pilImageRgbData = fn()
wxImage.SetData(pilImageRgbData)
@@ -1127,6 +1191,7 @@
do_doctest_gettext_workaround()
return doctest.testmod().failed
+
def registerPid(pid):
"""Register process id as GUI_PID GRASS variable
@@ -1138,7 +1203,8 @@
guiPid = env['GUI_PID'].split(',')
guiPid.append(str(pid))
grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
-
+
+
def unregisterPid(pid):
"""Unregister process id from GUI_PID GRASS variable
@@ -1147,12 +1213,15 @@
env = grass.gisenv()
if 'GUI_PID' not in env:
return
-
+
guiPid = env['GUI_PID'].split(',')
pid = str(os.getpid())
if pid in guiPid:
guiPid.remove(pid)
- grass.run_command('g.gisenv', set='GUI_PID={}'.format(','.join(guiPid)))
-
+ grass.run_command(
+ 'g.gisenv',
+ set='GUI_PID={}'.format(
+ ','.join(guiPid)))
+
if __name__ == '__main__':
sys.exit(doc_test())
Modified: grass/trunk/gui/wxpython/core/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/core/workspace.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/workspace.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,29 +20,30 @@
import wx
-from core.utils import normalize_whitespace, _
-from core.settings import UserSettings
-from core.gcmd import EncodeString, GetDefaultEncoding
-from nviz.main import NvizSettings
+from core.utils import normalize_whitespace, _
+from core.settings import UserSettings
+from core.gcmd import EncodeString, GetDefaultEncoding
+from nviz.main import NvizSettings
from grass.script import core as gcore
class ProcessWorkspaceFile:
+
def __init__(self, tree):
"""A ElementTree handler for the GXW XML file, as defined in
grass-gxw.dtd.
"""
self.tree = tree
self.root = self.tree.getroot()
-
+
#
# layer manager properties
#
- self.layerManager = { 'pos' : None, # window position
- 'size' : None, # window size
- 'cwd' : None } # current working directory
-
+ self.layerManager = {'pos': None, # window position
+ 'size': None, # window size
+ 'cwd': None} # current working directory
+
#
# list of mapdisplays
#
@@ -55,27 +56,27 @@
# nviz state
#
self.nviz_state = {}
-
- self.displayIndex = -1 # first display has index '0'
-
+
+ self.displayIndex = -1 # first display has index '0'
+
self.__processFile()
if NvizSettings:
self.nvizDefault = NvizSettings()
else:
self.nvizDefault = None
-
+
def __filterValue(self, value):
"""Filter value
-
+
:param value:
"""
value = value.replace('<', '<')
value = value.replace('>', '>')
-
+
return value
- def __getNodeText(self, node, tag, default = ''):
+ def __getNodeText(self, node, tag, default=''):
"""Get node text"""
p = node.find(tag)
if p is not None:
@@ -85,9 +86,9 @@
return ''
return normalize_whitespace(p.text)
-
+
return default
-
+
def __processFile(self):
"""Process workspace file"""
#
@@ -99,122 +100,126 @@
if posAttr:
posVal = map(int, posAttr.split(','))
try:
- self.layerManager['pos'] = (posVal[0], posVal[1])
+ self.layerManager['pos'] = (posVal[0], posVal[1])
self.layerManager['size'] = (posVal[2], posVal[3])
except:
pass
# current working directory
cwdPath = self.__getNodeText(node_lm, 'cwd')
if cwdPath:
- self.layerManager['cwd'] = cwdPath
-
+ self.layerManager['cwd'] = cwdPath
+
#
# displays
#
for display in self.root.findall('display'):
self.displayIndex += 1
-
+
# window position and size
posAttr = display.get('dim', '')
if posAttr:
posVal = map(int, posAttr.split(','))
try:
- pos = (posVal[0], posVal[1])
+ pos = (posVal[0], posVal[1])
size = (posVal[2], posVal[3])
except:
- pos = None
+ pos = None
size = None
- # this happens on Windows when mapwindow is minimized when saving workspace
+ # this happens on Windows when mapwindow is minimized when
+ # saving workspace
else:
if posVal[0] == -32000:
pos = None
size = None
else:
- pos = None
+ pos = None
size = None
-
+
extentAttr = display.get('extent', '')
if extentAttr:
# w, s, e, n
extent = map(float, extentAttr.split(','))
else:
extent = None
-
+
# projection
node_projection = display.find('projection')
if node_projection is not None:
- projection = { 'enabled' : True,
- 'epsg' : node_projection.get('epsg', ''),
- 'proj' : self.__getNodeText(node_projection, 'value') }
+ projection = {
+ 'enabled': True, 'epsg': node_projection.get(
+ 'epsg', ''), 'proj': self.__getNodeText(
+ node_projection, 'value')}
else:
- projection = { 'enabled' : False }
-
- self.displays.append( {
- "name" : display.get('name'),
- "render" : bool(int(display.get('render', "0"))),
- "mode" : int(display.get('mode', 0)),
- "showCompExtent" : bool(int(display.get('showCompExtent', "0"))),
- "pos" : pos,
- "size" : size,
- "extent" : extent,
- "tbres" : display.get('tbres', '0'),
- "alignExtent" : bool(int(display.get('alignExtent', "0"))),
- "constrainRes" : bool(int(display.get('constrainRes', "0"))),
- "projection" : projection,
- "viewMode" : display.get('viewMode', '2d')} )
-
+ projection = {'enabled': False}
+
+ self.displays.append({
+ "name": display.get('name'),
+ "render": bool(int(display.get('render', "0"))),
+ "mode": int(display.get('mode', 0)),
+ "showCompExtent": bool(int(display.get('showCompExtent', "0"))),
+ "pos": pos,
+ "size": size,
+ "extent": extent,
+ "tbres": display.get('tbres', '0'),
+ "alignExtent": bool(int(display.get('alignExtent', "0"))),
+ "constrainRes": bool(int(display.get('constrainRes', "0"))),
+ "projection": projection,
+ "viewMode": display.get('viewMode', '2d')})
+
# process all layers/groups in the display
self.__processLayers(display)
# process nviz_state
self.__processNvizState(display)
- def __processLayers(self, node, inGroup = -1):
+ def __processLayers(self, node, inGroup=-1):
"""Process layers/groups of selected display
-
+
:param node: display tree node
:param inGroup: in group -> index of group item otherwise -1
"""
for item in node.getchildren():
if item.tag == 'group':
# -> group
- self.layers.append( {
- "type" : 'group',
- "name" : item.get('name', ''),
- "checked" : bool(int(item.get('checked', "0"))),
- "opacity" : None,
- "cmd" : None,
- "group" : inGroup,
- "display" : self.displayIndex,
- "vdigit" : None,
- "nviz" : None})
-
- self.__processLayers(item, inGroup = len(self.layers) - 1) # process items in group
-
+ self.layers.append({
+ "type": 'group',
+ "name": item.get('name', ''),
+ "checked": bool(int(item.get('checked', "0"))),
+ "opacity": None,
+ "cmd": None,
+ "group": inGroup,
+ "display": self.displayIndex,
+ "vdigit": None,
+ "nviz": None})
+
+ self.__processLayers(
+ item, inGroup=len(
+ self.layers) - 1) # process items in group
+
elif item.tag == 'layer':
cmd, selected, vdigit, nviz = self.__processLayer(item)
lname = item.get('name', None)
if lname and '\\n' in lname:
lname = lname.replace('\\n', os.linesep)
-
- self.layers.append( {
- "type" : item.get('type', None),
- "name" : lname,
- "checked" : bool(int(item.get('checked', "0"))),
- "opacity" : float(item.get('opacity', '1.0')),
- "cmd" : cmd,
- "group" : inGroup,
- "display" : self.displayIndex,
- "selected" : selected,
- "vdigit" : vdigit,
- "nviz" : nviz } )
-
+
+ self.layers.append({
+ "type": item.get('type', None),
+ "name": lname,
+ "checked": bool(int(item.get('checked', "0"))),
+ "opacity": float(item.get('opacity', '1.0')),
+ "cmd": cmd,
+ "group": inGroup,
+ "display": self.displayIndex,
+ "selected": selected,
+ "vdigit": vdigit,
+ "nviz": nviz})
+
def __processLayer(self, layer):
"""Process layer item
:param layer: tree node
"""
cmd = list()
-
+
#
# layer attributes (task) - 2D settings
#
@@ -245,7 +250,7 @@
selected = True
else:
selected = False
-
+
#
# Vector digitizer settings
#
@@ -254,7 +259,7 @@
vdigit = self.__processLayerVdigit(node_vdigit)
else:
vdigit = None
-
+
#
# Nviz (3D settings)
#
@@ -263,7 +268,7 @@
nviz = self.__processLayerNviz(node_nviz)
else:
nviz = None
-
+
return (cmd, selected, vdigit, nviz)
def __processLayerVdigit(self, node_vdigit):
@@ -278,12 +283,12 @@
vdigit['geomAttr'] = dict()
type = node.get('type')
vdigit['geomAttr'][type] = dict()
- vdigit['geomAttr'][type]['column'] = node.get('column') # required
+ vdigit['geomAttr'][type]['column'] = node.get('column') # required
# default map units
vdigit['geomAttr'][type]['units'] = node.get('units', 'mu')
-
+
return vdigit
-
+
def __processLayerNviz(self, node_nviz):
"""Process 3D layer settings
@@ -307,9 +312,11 @@
for sec in ('lines', 'points'):
nviz['vector'][sec] = {}
if node_nviz.find('vlines'):
- self.__processLayerNvizVectorLines(nviz, node_nviz.find('vlines'))
+ self.__processLayerNvizVectorLines(
+ nviz, node_nviz.find('vlines'))
if node_nviz.find('vpoints'):
- self.__processLayerNvizVectorPoints(nviz, node_nviz.find('vpoints'))
+ self.__processLayerNvizVectorPoints(
+ nviz, node_nviz.find('vpoints'))
return nviz
@@ -343,7 +350,8 @@
tagName = str(node_draw.tag)
nvizData['surface'][tagName]['all'] = False
nvizData['surface'][tagName]['mode'] = {}
- nvizData['surface'][tagName]['mode']['value'] = -1 # to be calculated
+ nvizData['surface'][tagName]['mode'][
+ 'value'] = -1 # to be calculated
nvizData['surface'][tagName]['mode']['desc'] = {}
nvizData['surface'][tagName]['mode']['desc']['shading'] = \
str(node_draw.get('shading', ''))
@@ -424,7 +432,8 @@
for vol_type in ('isosurface', 'slice'):
nd = node_res.find(vol_type)
value = int(self.__getNodeText(nd, 'value'))
- nvizData['volume']['draw']['resolution'][vol_type] = {'value': value}
+ nvizData['volume']['draw']['resolution'][
+ vol_type] = {'value': value}
node_shading = node_draw.find('shading')
if node_shading is not None:
nvizData['volume']['draw']['shading'] = {}
@@ -432,7 +441,8 @@
nd = node_shading.find(vol_type)
value = int(self.__getNodeText(nd, 'value'))
desc = self.__getNodeText(nd, 'desc')
- nvizData['volume']['draw']['shading'][vol_type] = {'value': value, 'desc': desc}
+ nvizData['volume']['draw']['shading'][
+ vol_type] = {'value': value, 'desc': desc}
nvizData['volume']['isosurface'] = []
for isosurfaceNode in nodeVolume.findall('isosurface'):
@@ -453,13 +463,16 @@
isoDict[att]['value'] = float(value)
inout = isosurfaceNode.find('inout')
if inout is not None:
- isoDict['inout'] = {'value': int(float(inout.find('value').text))}
+ isoDict['inout'] = {'value': int(
+ float(inout.find('value').text))}
nvizData['volume']['isosurface'].append(isoDict)
-
+
nvizData['volume']['slice'] = []
for sliceNode in nodeVolume.findall('slice'):
sliceDict = {}
- sliceDict['transp'] = {'value': int(sliceNode.find('transp').find('value').text)}
+ sliceDict['transp'] = {
+ 'value': int(
+ sliceNode.find('transp').find('value').text)}
sliceDict['position'] = {}
for child in sliceNode.find('position'):
if child.tag == 'axis':
@@ -467,7 +480,7 @@
else:
sliceDict['position'][child.tag] = float(child.text)
nvizData['volume']['slice'].append(sliceDict)
-
+
# position
node_pos = nodeVolume.find('position')
if node_pos is not None:
@@ -486,14 +499,21 @@
:param nodeVector: nviz vector points node
"""
marker = str(nodePoints.get('marker', ''))
- markerId = list(UserSettings.Get(group='nviz', key='vector',
- subkey=['points', 'marker'], settings_type='internal')).index(marker)
+ markerId = list(
+ UserSettings.Get(
+ group='nviz',
+ key='vector',
+ subkey=[
+ 'points',
+ 'marker'],
+ settings_type='internal')).index(marker)
nvizData['vector']['points']['marker'] = {'value': markerId}
node_mode = nodePoints.find('mode')
if node_mode is not None:
nvizData['vector']['points']['mode'] = {}
- nvizData['vector']['points']['mode']['type'] = str(node_mode.get('type', 'surface'))
+ nvizData['vector']['points']['mode'][
+ 'type'] = str(node_mode.get('type', 'surface'))
nvizData['vector']['points']['mode']['surface'] = {}
nvizData['vector']['points']['mode']['surface']['value'] = []
nvizData['vector']['points']['mode']['surface']['show'] = []
@@ -502,8 +522,8 @@
for node_map in node_mode.findall('map'):
nvizData['vector']['points']['mode']['surface']['value'].append(
self.__processLayerNvizNode(node_map, 'name', str))
- nvizData['vector']['points']['mode']['surface']['show'].append(bool(
- self.__processLayerNvizNode(node_map, 'checked', int)))
+ nvizData['vector']['points']['mode']['surface']['show'].append(
+ bool(self.__processLayerNvizNode(node_map, 'checked', int)))
# color
self.__processLayerNvizNode(nodePoints, 'color', str,
@@ -524,12 +544,15 @@
# thematic
node_thematic = nodePoints.find('thematic')
thematic = nvizData['vector']['points']['thematic'] = {}
- thematic['rgbcolumn'] = self.__processLayerNvizNode(node_thematic, 'rgbcolumn', str)
- thematic['sizecolumn'] = self.__processLayerNvizNode(node_thematic, 'sizecolumn', str)
+ thematic['rgbcolumn'] = self.__processLayerNvizNode(
+ node_thematic, 'rgbcolumn', str)
+ thematic['sizecolumn'] = self.__processLayerNvizNode(
+ node_thematic, 'sizecolumn', str)
for col in ('rgbcolumn', 'sizecolumn'):
if thematic[col] == 'None':
thematic[col] = None
- thematic['layer'] = self.__processLayerNvizNode(node_thematic, 'layer', int)
+ thematic['layer'] = self.__processLayerNvizNode(
+ node_thematic, 'layer', int)
for use in ('usecolor', 'usesize', 'usewidth'):
if node_thematic.get(use, ''):
thematic[use] = int(node_thematic.get(use, '0'))
@@ -543,7 +566,8 @@
node_mode = nodeLines.find('mode')
if node_mode is not None:
nvizData['vector']['lines']['mode'] = {}
- nvizData['vector']['lines']['mode']['type'] = str(node_mode.get('type', ''))
+ nvizData['vector']['lines']['mode'][
+ 'type'] = str(node_mode.get('type', ''))
nvizData['vector']['lines']['mode']['surface'] = {}
nvizData['vector']['lines']['mode']['surface']['value'] = []
nvizData['vector']['lines']['mode']['surface']['show'] = []
@@ -552,8 +576,8 @@
for node_map in node_mode.findall('map'):
nvizData['vector']['lines']['mode']['surface']['value'].append(
self.__processLayerNvizNode(node_map, 'name', str))
- nvizData['vector']['lines']['mode']['surface']['show'].append(bool(
- self.__processLayerNvizNode(node_map, 'checked', int)))
+ nvizData['vector']['lines']['mode']['surface']['show'].append(
+ bool(self.__processLayerNvizNode(node_map, 'checked', int)))
# color
self.__processLayerNvizNode(nodeLines, 'color', str,
@@ -570,17 +594,20 @@
# thematic
node_thematic = nodeLines.find('thematic')
thematic = nvizData['vector']['lines']['thematic'] = {}
- thematic['rgbcolumn'] = self.__processLayerNvizNode(node_thematic, 'rgbcolumn', str)
- thematic['sizecolumn'] = self.__processLayerNvizNode(node_thematic, 'sizecolumn', str)
+ thematic['rgbcolumn'] = self.__processLayerNvizNode(
+ node_thematic, 'rgbcolumn', str)
+ thematic['sizecolumn'] = self.__processLayerNvizNode(
+ node_thematic, 'sizecolumn', str)
for col in ('rgbcolumn', 'sizecolumn'):
if thematic[col] == 'None':
thematic[col] = None
- thematic['layer'] = self.__processLayerNvizNode(node_thematic, 'layer', int)
+ thematic['layer'] = self.__processLayerNvizNode(
+ node_thematic, 'layer', int)
for use in ('usecolor', 'usesize', 'usewidth'):
if node_thematic.get(use, ''):
thematic[use] = int(node_thematic.get(use, '0'))
- def __processLayerNvizNode(self, node, tag, cast, dc = None):
+ def __processLayerNvizNode(self, node, tag, cast, dc=None):
"""Process given tag nviz/vector"""
node_tag = node.find(tag)
if node_tag is not None:
@@ -599,7 +626,7 @@
dc[tag]['value'] = value
else:
return value
-
+
def __processNvizState(self, node):
"""Process tag nviz_state"""
node_state = node.find('nviz_state')
@@ -612,36 +639,52 @@
node_view = node_state.find('view')
view = {}
iview = {}
-
+
node_position = node_view.find('v_position')
view['position'] = {}
- view['position']['x'] = self.__processLayerNvizNode(node_position, 'x', float)
- view['position']['y'] = self.__processLayerNvizNode(node_position, 'y', float)
+ view['position']['x'] = self.__processLayerNvizNode(
+ node_position, 'x', float)
+ view['position']['y'] = self.__processLayerNvizNode(
+ node_position, 'y', float)
node_persp = node_view.find('persp')
view['persp'] = {}
iview['persp'] = {}
- view['persp']['value'] = self.__processLayerNvizNode(node_persp, 'value', int)
- view['persp']['step'] = self.__processLayerNvizNode(node_persp, 'step', int)
- iview['persp']['min'] = self.__processLayerNvizNode(node_persp, 'min', int)
- iview['persp']['max'] = self.__processLayerNvizNode(node_persp, 'max', int)
+ view['persp']['value'] = self.__processLayerNvizNode(
+ node_persp, 'value', int)
+ view['persp']['step'] = self.__processLayerNvizNode(
+ node_persp, 'step', int)
+ iview['persp']['min'] = self.__processLayerNvizNode(
+ node_persp, 'min', int)
+ iview['persp']['max'] = self.__processLayerNvizNode(
+ node_persp, 'max', int)
node_height = node_view.find('v_height')
iview['height'] = {}
- iview['height']['value'] = self.__processLayerNvizNode(node_height, 'value', int)
- iview['height']['min'] = self.__processLayerNvizNode(node_height, 'min', int)
- iview['height']['max'] = self.__processLayerNvizNode(node_height, 'max', int)
+ iview['height']['value'] = self.__processLayerNvizNode(
+ node_height, 'value', int)
+ iview['height']['min'] = self.__processLayerNvizNode(
+ node_height, 'min', int)
+ iview['height']['max'] = self.__processLayerNvizNode(
+ node_height, 'max', int)
node_twist = node_view.find('twist')
view['twist'] = {}
iview['twist'] = {}
- view['twist']['value'] = self.__processLayerNvizNode(node_twist, 'value', int)
- iview['twist']['min'] = self.__processLayerNvizNode(node_twist, 'min', int)
- iview['twist']['max'] = self.__processLayerNvizNode(node_twist, 'max', int)
+ view['twist']['value'] = self.__processLayerNvizNode(
+ node_twist, 'value', int)
+ iview['twist']['min'] = self.__processLayerNvizNode(
+ node_twist, 'min', int)
+ iview['twist']['max'] = self.__processLayerNvizNode(
+ node_twist, 'max', int)
node_zexag = node_view.find('z-exag')
view['z-exag'] = {}
iview['z-exag'] = {}
- view['z-exag']['value'] = self.__processLayerNvizNode(node_zexag, 'value', float)
- view['z-exag']['min'] = self.__processLayerNvizNode(node_zexag, 'min', int)
- view['z-exag']['max'] = self.__processLayerNvizNode(node_zexag, 'max', int)
- iview['z-exag']['llRatio'] = self.__processLayerNvizNode(node_zexag, 'llRatio', float)
+ view[
+ 'z-exag']['value'] = self.__processLayerNvizNode(node_zexag, 'value', float)
+ view[
+ 'z-exag']['min'] = self.__processLayerNvizNode(node_zexag, 'min', int)
+ view[
+ 'z-exag']['max'] = self.__processLayerNvizNode(node_zexag, 'max', int)
+ iview[
+ 'z-exag']['llRatio'] = self.__processLayerNvizNode(node_zexag, 'llRatio', float)
node_focus = node_view.find('focus')
iview['focus'] = {}
iview['focus']['x'] = self.__processLayerNvizNode(node_focus, 'x', int)
@@ -664,12 +707,13 @@
if node_rot is not None:
rotation = node_rot.text
if rotation:
- iview['rotation'] = [float(item) for item in rotation.split(',')]
+ iview['rotation'] = [float(item)
+ for item in rotation.split(',')]
view['background'] = {}
color = self.__processLayerNvizNode(node_view, 'background_color', str)
view['background']['color'] = tuple(map(int, color.split(':')))
-
+
self.nviz_state['view'] = view
self.nviz_state['iview'] = iview
#
@@ -677,63 +721,78 @@
#
node_light = node_state.find('light')
light = {}
-
+
node_position = node_light.find('l_position')
light['position'] = {}
- light['position']['x'] = self.__processLayerNvizNode(node_position, 'x', float)
- light['position']['y'] = self.__processLayerNvizNode(node_position, 'y', float)
- light['position']['z'] = self.__processLayerNvizNode(node_position, 'z', int)
-
- light['bright'] = self.__processLayerNvizNode(node_light, 'bright', int)
- light['ambient'] = self.__processLayerNvizNode(node_light, 'ambient', int)
+ light['position']['x'] = self.__processLayerNvizNode(
+ node_position, 'x', float)
+ light['position']['y'] = self.__processLayerNvizNode(
+ node_position, 'y', float)
+ light['position']['z'] = self.__processLayerNvizNode(
+ node_position, 'z', int)
+
+ light['bright'] = self.__processLayerNvizNode(
+ node_light, 'bright', int)
+ light['ambient'] = self.__processLayerNvizNode(
+ node_light, 'ambient', int)
color = self.__processLayerNvizNode(node_light, 'color', str)
light['color'] = tuple(map(int, color.split(':')))
-
+
self.nviz_state['light'] = light
-
+
node_constants = node_state.find('constant_planes')
constants = []
if node_constants:
for node_plane in node_constants.findall('plane'):
plane = {}
- plane['color'] = self.__processLayerNvizNode(node_plane, 'color', str)
- plane['resolution'] = self.__processLayerNvizNode(node_plane, 'fine_resolution', int)
- plane['value'] = self.__processLayerNvizNode(node_plane, 'height', int)
+ plane['color'] = self.__processLayerNvizNode(
+ node_plane, 'color', str)
+ plane['resolution'] = self.__processLayerNvizNode(
+ node_plane, 'fine_resolution', int)
+ plane['value'] = self.__processLayerNvizNode(
+ node_plane, 'height', int)
plane['object'] = {}
constants.append({'constant': plane})
- self.nviz_state['constants'] = constants
+ self.nviz_state['constants'] = constants
+
class WriteWorkspaceFile(object):
"""Generic class for writing workspace file"""
+
def __init__(self, lmgr, file):
- self.file = file
+ self.file = file
self.lmgr = lmgr
self.indent = 0
-
+
# write header
- self.file.write('<?xml version="1.0" encoding="%s"?>\n' % GetDefaultEncoding(forceUTF8 = True))
+ self.file.write(
+ '<?xml version="1.0" encoding="%s"?>\n' %
+ GetDefaultEncoding(
+ forceUTF8=True))
self.file.write('<!DOCTYPE gxw SYSTEM "grass-gxw.dtd">\n')
self.file.write('%s<gxw>\n' % (' ' * self.indent))
-
- self.indent =+ 4
-
+
+ self.indent = + 4
+
# layer manager
windowPos = self.lmgr.GetPosition()
windowSize = self.lmgr.GetSize()
- file.write('%s<layer_manager dim="%d,%d,%d,%d">\n' % (' ' * self.indent,
- windowPos[0],
- windowPos[1],
- windowSize[0],
- windowSize[1]
- ))
+ file.write(
+ '%s<layer_manager dim="%d,%d,%d,%d">\n' %
+ (' ' *
+ self.indent,
+ windowPos[0],
+ windowPos[1],
+ windowSize[0],
+ windowSize[1]))
self.indent += 4
cwdPath = self.lmgr.GetCwdPath()
if cwdPath:
file.write('%s<cwd>%s</cwd>\n' % (' ' * self.indent, cwdPath))
self.indent -= 4
file.write('%s</layer_manager>\n' % (' ' * self.indent))
-
+
# list of displays
for page in range(0, self.lmgr.GetLayerNotebook().GetPageCount()):
dispName = self.lmgr.GetLayerNotebook().GetPageText(page)
@@ -741,14 +800,14 @@
region = mapTree.GetMap().GetCurrentRegion()
compRegion = gcore.region(region3d=True)
mapdisp = mapTree.GetMapDisplay()
-
+
displayPos = mapdisp.GetPosition()
displaySize = mapdisp.GetSize()
if mapdisp.toolbars['map'].combo.GetSelection() == 1:
viewmode = '3d'
else:
viewmode = '2d'
-
+
file.write('%s<display '
'name="%s" render="%d" '
'mode="%d" showCompExtent="%d" '
@@ -778,84 +837,98 @@
viewmode
))
# projection statusbar info
- if mapdisp.GetProperty('projection') and \
- UserSettings.Get(group='display', key='projection', subkey='proj4'):
+ if mapdisp.GetProperty('projection') and UserSettings.Get(
+ group='display', key='projection', subkey='proj4'):
self.indent += 4
file.write('%s<projection' % (' ' * self.indent))
- epsg = UserSettings.Get(group='display', key='projection', subkey='epsg')
+ epsg = UserSettings.Get(
+ group='display', key='projection', subkey='epsg')
if epsg:
file.write(' epsg="%s"' % epsg)
file.write('>\n')
- proj = UserSettings.Get(group='display', key='projection', subkey='proj4')
- self.indent += 4
+ proj = UserSettings.Get(
+ group='display', key='projection', subkey='proj4')
+ self.indent += 4
file.write('%s<value>%s</value>\n' % (' ' * self.indent, proj))
self.indent -= 4
file.write('%s</projection>\n' % (' ' * self.indent))
self.indent -= 4
-
+
# list of layers
item = mapTree.GetFirstChild(mapTree.root)[0]
self.__writeLayer(mapTree, item)
-
+
if mapdisp.MapWindow3D is not None:
nvizDisp = mapdisp.MapWindow3D
- self.__writeNvizState(view = nvizDisp.view, iview = nvizDisp.iview,
- light = nvizDisp.light, constants = nvizDisp.constants)
-
+ self.__writeNvizState(
+ view=nvizDisp.view,
+ iview=nvizDisp.iview,
+ light=nvizDisp.light,
+ constants=nvizDisp.constants)
+
file.write('%s</display>\n' % (' ' * self.indent))
-
- self.indent =- 4
+
+ self.indent = - 4
file.write('%s</gxw>\n' % (' ' * self.indent))
def __filterValue(self, value):
"""Make value XML-valid"""
value = value.replace('<', '<')
value = value.replace('>', '>')
-
+
return value
-
+
def __writeLayer(self, mapTree, item):
"""Write bunch of layers to GRASS Workspace XML file"""
self.indent += 4
itemSelected = mapTree.GetSelections()
while item and item.IsOk():
- type = mapTree.GetLayerInfo(item, key = 'type')
+ type = mapTree.GetLayerInfo(item, key='type')
if type != 'group':
- maplayer = mapTree.GetLayerInfo(item, key = 'maplayer')
+ maplayer = mapTree.GetLayerInfo(item, key='maplayer')
else:
maplayer = None
checked = int(item.IsChecked())
if type == 'command':
- cmd = mapTree.GetLayerInfo(item, key = 'maplayer').GetCmd(string=True)
- self.file.write('%s<layer type="%s" name="%s" checked="%d">\n' % \
- (' ' * self.indent, type, EncodeString(cmd), checked))
+ cmd = mapTree.GetLayerInfo(
+ item, key='maplayer').GetCmd(
+ string=True)
+ self.file.write(
+ '%s<layer type="%s" name="%s" checked="%d">\n' %
+ (' ' * self.indent, type, EncodeString(cmd), checked))
self.file.write('%s</layer>\n' % (' ' * self.indent))
elif type == 'group':
name = mapTree.GetItemText(item)
- self.file.write('%s<group name="%s" checked="%d">\n' % \
- (' ' * self.indent, EncodeString(name), checked))
+ self.file.write(
+ '%s<group name="%s" checked="%d">\n' %
+ (' ' * self.indent, EncodeString(name), checked))
self.indent += 4
subItem = mapTree.GetFirstChild(item)[0]
self.__writeLayer(mapTree, subItem)
self.indent -= 4
- self.file.write('%s</group>\n' % (' ' * self.indent));
+ self.file.write('%s</group>\n' % (' ' * self.indent))
else:
- cmd = mapTree.GetLayerInfo(item, key = 'maplayer').GetCmd(string = False)
+ cmd = mapTree.GetLayerInfo(
+ item, key='maplayer').GetCmd(
+ string=False)
name = mapTree.GetItemText(item).replace(os.linesep, '\\n')
opacity = maplayer.GetOpacity()
# remove 'opacity' part
if opacity < 1:
name = name.split('(', -1)[0].strip()
- self.file.write('%s<layer type="%s" name="%s" checked="%d" opacity="%f">\n' % \
- (' ' * self.indent, type, EncodeString(name), checked, opacity));
-
+ self.file.write(
+ '%s<layer type="%s" name="%s" checked="%d" opacity="%f">\n' %
+ (' ' * self.indent, type, EncodeString(name), checked, opacity))
+
self.indent += 4
# selected ?
if item in itemSelected:
self.file.write('%s<selected />\n' % (' ' * self.indent))
# layer properties
- self.file.write('%s<task name="%s">\n' % (' ' * self.indent, cmd[0]))
+ self.file.write(
+ '%s<task name="%s">\n' %
+ (' ' * self.indent, cmd[0]))
self.indent += 4
for key, val in cmd[1].iteritems():
if key == 'flags':
@@ -865,18 +938,21 @@
elif val in (True, False):
self.file.write('%s<flag name="%s" />\n' %
(' ' * self.indent, key))
- else: # parameter
+ else: # parameter
self.file.write('%s<parameter name="%s">\n' %
(' ' * self.indent, key))
self.indent += 4
- self.file.write('%s<value>%s</value>\n' %
- (' ' * self.indent, self.__filterValue(val)))
+ self.file.write(
+ '%s<value>%s</value>\n' %
+ (' ' * self.indent, self.__filterValue(val)))
self.indent -= 4
- self.file.write('%s</parameter>\n' % (' ' * self.indent))
+ self.file.write(
+ '%s</parameter>\n' %
+ (' ' * self.indent))
self.indent -= 4
self.file.write('%s</task>\n' % (' ' * self.indent))
# vector digitizer
- vdigit = mapTree.GetLayerInfo(item, key = 'vdigit')
+ vdigit = mapTree.GetLayerInfo(item, key='vdigit')
if vdigit:
self.file.write('%s<vdigit>\n' % (' ' * self.indent))
if 'geomAttr' in vdigit:
@@ -885,12 +961,13 @@
units = ''
if val['units'] != 'mu':
units = ' units="%s"' % val['units']
- self.file.write('%s<geometryAttribute type="%s" column="%s"%s />\n' % \
- (' ' * self.indent, type, val['column'], units))
+ self.file.write(
+ '%s<geometryAttribute type="%s" column="%s"%s />\n' %
+ (' ' * self.indent, type, val['column'], units))
self.indent -= 4
self.file.write('%s</vdigit>\n' % (' ' * self.indent))
# nviz
- nviz = mapTree.GetLayerInfo(item, key = 'nviz')
+ nviz = mapTree.GetLayerInfo(item, key='nviz')
if nviz:
self.file.write('%s<nviz>\n' % (' ' * self.indent))
if maplayer.type == 'raster':
@@ -904,70 +981,80 @@
self.file.write('%s</layer>\n' % (' ' * self.indent))
item = mapTree.GetNextSibling(item)
self.indent -= 4
-
+
def __writeNvizSurface(self, data):
"""Save Nviz raster layer properties to workspace
:param data: Nviz layer properties
"""
- if 'object' not in data: # skip disabled
+ if 'object' not in data: # skip disabled
return
self.indent += 4
self.file.write('%s<surface>\n' % (' ' * self.indent))
self.indent += 4
for attrb in data.iterkeys():
- if len(data[attrb]) < 1: # skip empty attributes
+ if len(data[attrb]) < 1: # skip empty attributes
continue
if attrb == 'object':
continue
-
+
for name in data[attrb].iterkeys():
# surface attribute
if attrb == 'attribute':
if data[attrb][name]['map'] is None:
continue
- self.file.write('%s<%s name="%s" map="%d">\n' % \
- (' ' * self.indent, attrb, name, data[attrb][name]['map']))
+ self.file.write(
+ '%s<%s name="%s" map="%d">\n' %
+ (' ' * self.indent, attrb, name, data[attrb][name]['map']))
self.indent += 4
- self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+ self.file.write(
+ '%s<value>%s</value>\n' %
+ (' ' * self.indent, data[attrb][name]['value']))
self.indent -= 4
# end tag
self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
# draw mode
if attrb == 'draw':
- self.file.write('%s<%s' %(' ' * self.indent, attrb))
+ self.file.write('%s<%s' % (' ' * self.indent, attrb))
if 'mode' in data[attrb]:
for tag, value in data[attrb]['mode']['desc'].iteritems():
self.file.write(' %s="%s"' % (tag, value))
- self.file.write('>\n') # <draw ...>
+ self.file.write('>\n') # <draw ...>
if 'resolution' in data[attrb]:
self.indent += 4
for type in ('coarse', 'fine'):
- self.file.write('%s<resolution type="%s">\n' % (' ' * self.indent, type))
+ self.file.write(
+ '%s<resolution type="%s">\n' %
+ (' ' * self.indent, type))
self.indent += 4
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent,
- data[attrb]['resolution'][type]))
+ self.file.write(
+ '%s<value>%d</value>\n' %
+ (' ' * self.indent, data[attrb]['resolution'][type]))
self.indent -= 4
- self.file.write('%s</resolution>\n' % (' ' * self.indent))
+ self.file.write(
+ '%s</resolution>\n' %
+ (' ' * self.indent))
if 'wire-color' in data[attrb]:
self.file.write('%s<wire_color>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<value>%s</value>\n' % (' ' * self.indent,
- data[attrb]['wire-color']['value']))
+ self.file.write(
+ '%s<value>%s</value>\n' %
+ (' ' * self.indent, data[attrb]['wire-color']['value']))
self.indent -= 4
self.file.write('%s</wire_color>\n' % (' ' * self.indent))
self.indent -= 4
-
+
# position
elif attrb == 'position':
- self.file.write('%s<%s>\n' %(' ' * self.indent, attrb))
+ self.file.write('%s<%s>\n' % (' ' * self.indent, attrb))
for tag in ('x', 'y', 'z'):
self.indent += 4
- self.file.write('%s<%s>%d</%s>\n' % (' ' * self.indent, tag,
- data[attrb][tag], tag))
+ self.file.write(
+ '%s<%s>%d</%s>\n' %
+ (' ' * self.indent, tag, data[attrb][tag], tag))
self.indent -= 4
if attrb != 'attribute':
@@ -999,10 +1086,13 @@
# surface attribute
if data[attrb][name]['map'] is None:
continue
- self.file.write('%s<%s name="%s" map="%d">\n' %
- (' ' * self.indent, attrb, name, data[attrb][name]['map']))
+ self.file.write(
+ '%s<%s name="%s" map="%d">\n' %
+ (' ' * self.indent, attrb, name, data[attrb][name]['map']))
self.indent += 4
- self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+ self.file.write(
+ '%s<value>%s</value>\n' %
+ (' ' * self.indent, data[attrb][name]['value']))
self.indent -= 4
# end tag
self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
@@ -1017,30 +1107,42 @@
self.file.write('%s<%s>\n' % (' ' * self.indent, att))
for type in ('isosurface', 'slice'):
self.indent += 4
- self.file.write('%s<%s>\n' % (' ' * self.indent, type))
+ self.file.write(
+ '%s<%s>\n' %
+ (' ' * self.indent, type))
self.indent += 4
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent,
- data[attrb][att][type]['value']))
+ self.file.write(
+ '%s<value>%d</value>\n' %
+ (' ' * self.indent, data[attrb][att][type]['value']))
if att == 'shading':
- self.file.write('%s<desc>%s</desc>\n' % (' ' * self.indent,
- data[attrb][att][type]['desc']))
+ self.file.write(
+ '%s<desc>%s</desc>\n' %
+ (' ' * self.indent, data[attrb][att][type]['desc']))
self.indent -= 4
- self.file.write('%s</%s>\n' % (' ' * self.indent, type))
+ self.file.write(
+ '%s</%s>\n' %
+ (' ' * self.indent, type))
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, att))
if 'box' in data[attrb]:
self.file.write('%s<box>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<enabled>%d</enabled>\n' % (' ' * self.indent, data[attrb]['box']['enabled']))
+ self.file.write(
+ '%s<enabled>%d</enabled>\n' %
+ (' ' * self.indent, data[attrb]['box']['enabled']))
self.indent -= 4
self.file.write('%s</box>\n' % (' ' * self.indent))
if 'mode' in data[attrb]:
self.file.write('%s<mode>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<desc>%s</desc>\n' % (' ' * self.indent, data[attrb]['mode']['desc']))
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, data[attrb]['mode']['value']))
+ self.file.write(
+ '%s<desc>%s</desc>\n' %
+ (' ' * self.indent, data[attrb]['mode']['desc']))
+ self.file.write(
+ '%s<value>%d</value>\n' %
+ (' ' * self.indent, data[attrb]['mode']['value']))
self.indent -= 4
self.file.write('%s</mode>\n' % (' ' * self.indent))
self.indent -= 4
@@ -1050,8 +1152,15 @@
self.file.write('%s<%s>\n' % (' ' * self.indent, attrb))
for tag in ('x', 'y', 'z'):
self.indent += 4
- self.file.write('%s<%s>%d</%s>\n' % (' ' * self.indent, tag,
- data[attrb].get(tag, 0), tag))
+ self.file.write(
+ '%s<%s>%d</%s>\n' %
+ (' ' *
+ self.indent,
+ tag,
+ data[attrb].get(
+ tag,
+ 0),
+ tag))
self.indent -= 4
if attrb == 'isosurface':
for isosurface in data[attrb]:
@@ -1072,11 +1181,15 @@
except TypeError: # None
val = ''
self.indent += 4
- self.file.write(('%s<%s>' % (' ' * self.indent, att)) + val)
+ self.file.write(
+ ('%s<%s>' %
+ (' ' * self.indent, att)) + val)
self.file.write('</%s>\n' % att)
self.indent -= 4
# end tag
- self.file.write('%s</%s>\n' % (' ' * self.indent, name))
+ self.file.write(
+ '%s</%s>\n' %
+ (' ' * self.indent, name))
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
@@ -1091,11 +1204,15 @@
continue
val = slice_[name][att]
self.indent += 4
- self.file.write(('%s<%s>' % (' ' * self.indent, att)) + str(val))
+ self.file.write(
+ ('%s<%s>' %
+ (' ' * self.indent, att)) + str(val))
self.file.write('</%s>\n' % att)
self.indent -= 4
# end tag
- self.file.write('%s</%s>\n' % (' ' * self.indent, name))
+ self.file.write(
+ '%s</%s>\n' %
+ (' ' * self.indent, name))
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, attrb))
if attrb not in ('attribute', 'isosurface', 'slice'):
@@ -1113,17 +1230,18 @@
"""
self.indent += 4
for attrb in data.iterkeys():
- if len(data[attrb]) < 1: # skip empty attributes
+ if len(data[attrb]) < 1: # skip empty attributes
continue
- if 'object' not in data[attrb]: # skip disabled
+ if 'object' not in data[attrb]: # skip disabled
continue
if attrb == 'lines':
self.file.write('%s<v%s>\n' % (' ' * self.indent, attrb))
elif attrb == 'points':
markerId = data[attrb]['marker']['value']
- marker = UserSettings.Get(group = 'nviz', key = 'vector',
- subkey = ['points', 'marker'], settings_type='internal')[markerId]
+ marker = UserSettings.Get(
+ group='nviz', key='vector', subkey=[
+ 'points', 'marker'], settings_type='internal')[markerId]
self.file.write('%s<v%s marker="%s">\n' % (' ' * self.indent,
attrb,
marker))
@@ -1132,16 +1250,22 @@
if name in ('object', 'marker'):
continue
if name == 'mode':
- self.file.write('%s<%s type="%s">\n' % (' ' * self.indent, name,
- data[attrb][name]['type']))
+ self.file.write(
+ '%s<%s type="%s">\n' %
+ (' ' * self.indent, name, data[attrb][name]['type']))
if data[attrb][name]['type'] == 'surface':
self.indent += 4
- for idx, surface in enumerate(data[attrb][name]['surface']['value']):
+ for idx, surface in enumerate(
+ data[attrb][name]['surface']['value']):
checked = data[attrb][name]['surface']['show'][idx]
self.file.write('%s<map>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<name>%s</name>\n' % (' ' * self.indent, surface))
- self.file.write('%s<checked>%s</checked>\n' % (' ' * self.indent, int(checked)))
+ self.file.write(
+ '%s<name>%s</name>\n' %
+ (' ' * self.indent, surface))
+ self.file.write(
+ '%s<checked>%s</checked>\n' %
+ (' ' * self.indent, int(checked)))
self.indent -= 4
self.file.write('%s</map>\n' % (' ' * self.indent))
self.indent -= 4
@@ -1150,7 +1274,9 @@
self.file.write('%s<%s ' % (' ' * self.indent, name))
for key in data[attrb][name].iterkeys():
if key.startswith('use'):
- self.file.write('%s="%s" ' % (key, int(data[attrb][name][key])))
+ self.file.write(
+ '%s="%s" ' %
+ (key, int(data[attrb][name][key])))
self.file.write('>\n')
self.indent += 4
for key, value in data[attrb][name].iteritems():
@@ -1158,13 +1284,17 @@
continue
if value is None:
value = ''
- self.file.write('%s<%s>%s</%s>\n' % (' ' * self.indent, key, value, key))
+ self.file.write(
+ '%s<%s>%s</%s>\n' %
+ (' ' * self.indent, key, value, key))
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, name))
else:
self.file.write('%s<%s>\n' % (' ' * self.indent, name))
self.indent += 4
- self.file.write('%s<value>%s</value>\n' % (' ' * self.indent, data[attrb][name]['value']))
+ self.file.write(
+ '%s<value>%s</value>\n' %
+ (' ' * self.indent, data[attrb][name]['value']))
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, name))
self.indent -= 4
@@ -1190,59 +1320,91 @@
# position
self.file.write('%s<v_position>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<x>%.2f</x>\n' % (' ' * self.indent, view['position']['x']))
- self.file.write('%s<y>%.2f</y>\n' % (' ' * self.indent, view['position']['y']))
+ self.file.write(
+ '%s<x>%.2f</x>\n' %
+ (' ' * self.indent, view['position']['x']))
+ self.file.write(
+ '%s<y>%.2f</y>\n' %
+ (' ' * self.indent, view['position']['y']))
self.indent -= 4
self.file.write('%s</v_position>\n' % (' ' * self.indent))
# perspective
self.file.write('%s<persp>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, view['persp']['value']))
- self.file.write('%s<step>%d</step>\n' % (' ' * self.indent, view['persp']['step']))
- self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['persp']['min']))
- self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['persp']['max']))
+ self.file.write('%s<value>%d</value>\n' %
+ (' ' * self.indent, view['persp']['value']))
+ self.file.write('%s<step>%d</step>\n' %
+ (' ' * self.indent, view['persp']['step']))
+ self.file.write('%s<min>%d</min>\n' %
+ (' ' * self.indent, iview['persp']['min']))
+ self.file.write('%s<max>%d</max>\n' %
+ (' ' * self.indent, iview['persp']['max']))
self.indent -= 4
self.file.write('%s</persp>\n' % (' ' * self.indent))
# height
self.file.write('%s<v_height>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, iview['height']['value']))
- self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['height']['min']))
- self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['height']['max']))
+ self.file.write('%s<value>%d</value>\n' %
+ (' ' * self.indent, iview['height']['value']))
+ self.file.write('%s<min>%d</min>\n' %
+ (' ' * self.indent, iview['height']['min']))
+ self.file.write('%s<max>%d</max>\n' %
+ (' ' * self.indent, iview['height']['max']))
self.indent -= 4
self.file.write('%s</v_height>\n' % (' ' * self.indent))
# twist
self.file.write('%s<twist>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<value>%d</value>\n' % (' ' * self.indent, view['twist']['value']))
- self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, iview['twist']['min']))
- self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, iview['twist']['max']))
+ self.file.write('%s<value>%d</value>\n' %
+ (' ' * self.indent, view['twist']['value']))
+ self.file.write('%s<min>%d</min>\n' %
+ (' ' * self.indent, iview['twist']['min']))
+ self.file.write('%s<max>%d</max>\n' %
+ (' ' * self.indent, iview['twist']['max']))
self.indent -= 4
self.file.write('%s</twist>\n' % (' ' * self.indent))
# z-exag
self.file.write('%s<z-exag>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<value>%.2f</value>\n' % (' ' * self.indent, view['z-exag']['value']))
- self.file.write('%s<min>%d</min>\n' % (' ' * self.indent, view['z-exag']['min']))
- self.file.write('%s<max>%d</max>\n' % (' ' * self.indent, view['z-exag']['max']))
- self.file.write('%s<llRatio>%.2f</llRatio>\n' % (' ' * self.indent, iview['z-exag']['llRatio']))
+ self.file.write('%s<value>%.2f</value>\n' %
+ (' ' * self.indent, view['z-exag']['value']))
+ self.file.write('%s<min>%d</min>\n' %
+ (' ' * self.indent, view['z-exag']['min']))
+ self.file.write('%s<max>%d</max>\n' %
+ (' ' * self.indent, view['z-exag']['max']))
+ self.file.write('%s<llRatio>%.2f</llRatio>\n' %
+ (' ' * self.indent, iview['z-exag']['llRatio']))
self.indent -= 4
self.file.write('%s</z-exag>\n' % (' ' * self.indent))
# focus (look here)
self.file.write('%s<focus>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<x>%d</x>\n' % (' ' * self.indent, iview['focus']['x']))
- self.file.write('%s<y>%d</y>\n' % (' ' * self.indent, iview['focus']['y']))
- self.file.write('%s<z>%d</z>\n' % (' ' * self.indent, iview['focus']['z']))
+ self.file.write(
+ '%s<x>%d</x>\n' %
+ (' ' * self.indent, iview['focus']['x']))
+ self.file.write(
+ '%s<y>%d</y>\n' %
+ (' ' * self.indent, iview['focus']['y']))
+ self.file.write(
+ '%s<z>%d</z>\n' %
+ (' ' * self.indent, iview['focus']['z']))
self.indent -= 4
self.file.write('%s</focus>\n' % (' ' * self.indent))
# rotation
- rotation = ','.join([str(i) for i in iview['rotation']]) if iview.get('rotation', '') else ''
- self.file.write('%s<rotation>%s</rotation>\n' % (' ' * self.indent, rotation))
+ rotation = ','.join(
+ [str(i) for i in iview['rotation']]) if iview.get(
+ 'rotation', '') else ''
+ self.file.write(
+ '%s<rotation>%s</rotation>\n' %
+ (' ' * self.indent, rotation))
# background
- self.__writeTagWithValue('background_color', view['background']['color'][:3], format = 'd:%d:%d')
-
+ self.__writeTagWithValue(
+ 'background_color',
+ view['background']['color'][
+ :3],
+ format='d:%d:%d')
+
self.indent -= 4
self.file.write('%s</view>\n' % (' ' * self.indent))
#
@@ -1253,9 +1415,15 @@
# position
self.file.write('%s<l_position>\n' % (' ' * self.indent))
self.indent += 4
- self.file.write('%s<x>%.2f</x>\n' % (' ' * self.indent, light['position']['x']))
- self.file.write('%s<y>%.2f</y>\n' % (' ' * self.indent, light['position']['y']))
- self.file.write('%s<z>%d</z>\n' % (' ' * self.indent, light['position']['z']))
+ self.file.write(
+ '%s<x>%.2f</x>\n' %
+ (' ' * self.indent, light['position']['x']))
+ self.file.write(
+ '%s<y>%.2f</y>\n' %
+ (' ' * self.indent, light['position']['y']))
+ self.file.write(
+ '%s<z>%d</z>\n' %
+ (' ' * self.indent, light['position']['z']))
self.indent -= 4
self.file.write('%s</l_position>\n' % (' ' * self.indent))
# bright
@@ -1263,8 +1431,8 @@
# ambient
self.__writeTagWithValue('ambient', light['ambient'])
# color
- self.__writeTagWithValue('color', light['color'][:3], format = 'd:%d:%d')
-
+ self.__writeTagWithValue('color', light['color'][:3], format='d:%d:%d')
+
self.indent -= 4
self.file.write('%s</light>\n' % (' ' * self.indent))
#
@@ -1276,21 +1444,25 @@
for idx, plane in enumerate(constants):
self.file.write('%s<plane>\n' % (' ' * self.indent))
self.indent += 4
- self.__writeTagWithValue('height', constants[idx]['constant']['value'])
- self.__writeTagWithValue('fine_resolution', constants[idx]['constant']['resolution'])
- self.__writeTagWithValue('color', constants[idx]['constant']['color'], format = 's')
+ self.__writeTagWithValue(
+ 'height', constants[idx]['constant']['value'])
+ self.__writeTagWithValue(
+ 'fine_resolution',
+ constants[idx]['constant']['resolution'])
+ self.__writeTagWithValue(
+ 'color', constants[idx]['constant']['color'], format='s')
self.indent -= 4
self.file.write('%s</plane>\n' % (' ' * self.indent))
self.indent -= 4
self.file.write('%s</constant_planes>\n' % (' ' * self.indent))
self.indent -= 4
-
+
self.file.write('%s</nviz_state>\n' % (' ' * self.indent))
self.indent -= 4
-
- def __writeTagWithValue(self, tag, data, format = 'd'):
+
+ def __writeTagWithValue(self, tag, data, format='d'):
"""Helper function for writing pair tag
-
+
:param tag: written tag
:param data: written data
:param format: conversion type
@@ -1301,8 +1473,10 @@
self.file.write(('<value>%' + format + '</value>\n') % data)
self.indent -= 4
self.file.write('%s</%s>\n' % (' ' * self.indent, tag))
-
+
+
class ProcessGrcFile(object):
+
def __init__(self, filename):
"""Process GRC file"""
self.filename = filename
@@ -1329,26 +1503,34 @@
try:
file = open(self.filename, "r")
except IOError:
- wx.MessageBox(parent=parent,
- message=_("Unable to open file <%s> for reading.") % self.filename,
- caption=_("Error"), style=wx.OK | wx.ICON_ERROR)
+ wx.MessageBox(
+ parent=parent,
+ message=_("Unable to open file <%s> for reading.") %
+ self.filename,
+ caption=_("Error"),
+ style=wx.OK | wx.ICON_ERROR)
return []
line_id = 1
for line in file.readlines():
self.process_line(line.rstrip('\n'), line_id)
- line_id +=1
+ line_id += 1
file.close()
if self.num_error > 0:
- wx.MessageBox(parent=parent,
- message=_("Some lines were skipped when reading settings "
- "from file <%(file)s>.\nSee 'Command output' window for details.\n\n"
- "Number of skipped lines: %(line)d") % \
- { 'file' : self.filename, 'line' : self.num_error },
- caption=_("Warning"), style=wx.OK | wx.ICON_EXCLAMATION)
- parent._gconsole.WriteLog('Map layers loaded from GRC file <%s>' % self.filename)
+ wx.MessageBox(
+ parent=parent,
+ message=_(
+ "Some lines were skipped when reading settings "
+ "from file <%(file)s>.\nSee 'Command output' window for details.\n\n"
+ "Number of skipped lines: %(line)d") %
+ {'file': self.filename, 'line': self.num_error},
+ caption=_("Warning"),
+ style=wx.OK | wx.ICON_EXCLAMATION)
+ parent._gconsole.WriteLog(
+ 'Map layers loaded from GRC file <%s>' %
+ self.filename)
parent._gconsole.WriteLog('Skipped lines:\n%s' % self.error)
return self.layers
@@ -1359,21 +1541,21 @@
if element == 'Group':
self.groupName = self._get_value(line)
self.layers.append({
- "type" : 'group',
- "name" : self.groupName,
- "checked" : None,
- "opacity" : None,
- "cmd" : None,
- "group" : self.inGroup,
- "display" : 0 })
+ "type": 'group',
+ "name": self.groupName,
+ "checked": None,
+ "opacity": None,
+ "cmd": None,
+ "group": self.inGroup,
+ "display": 0})
self.inGroup = True
elif element == '_check':
- if int(self._get_value(line)) == 1:
+ if int(self._get_value(line)) == 1:
self.layers[-1]['checked'] = True
else:
self.layers[-1]['checked'] = False
-
+
elif element == 'End':
if self.inRaster:
self.inRaster = False
@@ -1383,7 +1565,7 @@
self.inGroup = False
elif self.inGridline:
self.inGridline = False
-
+
elif element == 'opacity':
self.layers[-1]['opacity'] = float(self._get_value(line))
@@ -1391,26 +1573,26 @@
elif element == 'Raster':
self.inRaster = True
self.layers.append({
- "type" : 'raster',
- "name" : self._get_value(line),
- "checked" : None,
- "opacity" : None,
- "cmd" : ['d.rast'],
- "group" : self.inGroup,
- "display" : 0})
+ "type": 'raster',
+ "name": self._get_value(line),
+ "checked": None,
+ "opacity": None,
+ "cmd": ['d.rast'],
+ "group": self.inGroup,
+ "display": 0})
elif element == 'map' and self.inRaster:
self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
-
+
elif element == 'overlay' and self.inRaster:
if int(self._get_value(line)) == 1:
self.layers[-1]['cmd'].append('-o')
-
+
elif element == 'rastquery' and self.inRaster:
value = self._get_value(line)
if value != '':
self.layers[-1]['cmd'].append('catlist=%s' % value)
-
+
elif element == 'bkcolor' and self.inRaster:
value = self._get_value(line)
if value != '':
@@ -1420,17 +1602,17 @@
elif element == 'Vector':
self.inVector = True
self.layers.append({
- "type" : 'vector',
- "name" : self._get_value(line),
- "checked" : None,
- "opacity" : None,
- "cmd" : ['d.vect'],
- "group" : self.inGroup,
- "display" : 0})
+ "type": 'vector',
+ "name": self._get_value(line),
+ "checked": None,
+ "opacity": None,
+ "cmd": ['d.vect'],
+ "group": self.inGroup,
+ "display": 0})
elif element == 'vector' and self.inVector:
self.layers[-1]['cmd'].append('map=%s' % self._get_value(line))
-
+
elif element in ('display_shape',
'display_cat',
'display_topo',
@@ -1442,11 +1624,12 @@
'type_centroid',
'type_area',
'type_face') and self.inVector:
-
+
if int(self._get_value(line)) == 1:
name = element.split('_')[0]
type = element.split('_')[1]
- paramId = self._get_cmd_param_index(self.layers[-1]['cmd'], name)
+ paramId = self._get_cmd_param_index(
+ self.layers[-1]['cmd'], name)
if paramId == -1:
self.layers[-1]['cmd'].append('%s=%s' % (name, type))
else:
@@ -1457,8 +1640,8 @@
'lcolor') and self.inVector:
value = self._get_value(line)
if value != '':
- self.layers[-1]['cmd'].append('%s=%s' % (element,
- self._color_name_to_rgb(value)))
+ self.layers[-1]['cmd'].append('%s=%s' %
+ (element, self._color_name_to_rgb(value)))
elif element == 'rdmcolor' and self.inVector:
if int(self._get_value(line)) == 1:
@@ -1481,7 +1664,7 @@
if value != '':
self.layers[-1]['cmd'].append('%s=%s' % (element,
value))
-
+
elif element == 'lwidth':
value = self._get_value(line)
if value != '':
@@ -1491,7 +1674,7 @@
value = self._get_value(line)
if value != '':
self.layers[-1]['cmd'].append('llayer=%s' % value)
-
+
elif element == 'attribute':
value = self._get_value(line)
if value != '':
@@ -1506,28 +1689,31 @@
elif element == 'gridline':
self.inGridline = True
self.layers.append({
- "type" : 'grid',
- "name" : self._get_value(line),
- "checked" : None,
- "opacity" : None,
- "cmd" : ['d.grid'],
- "group" : self.inGroup,
- "display" : 0})
+ "type": 'grid',
+ "name": self._get_value(line),
+ "checked": None,
+ "opacity": None,
+ "cmd": ['d.grid'],
+ "group": self.inGroup,
+ "display": 0})
elif element == 'gridcolor':
value = self._get_value(line)
if value != '':
- self.layers[-1]['cmd'].append('color=%s' % self._color_name_to_rgb(value))
+ self.layers[-1]['cmd'].append('color=%s' %
+ self._color_name_to_rgb(value))
elif element == 'gridborder':
value = self._get_value(line)
if value != '':
- self.layers[-1]['cmd'].append('bordercolor=%s' % self._color_name_to_rgb(value))
+ self.layers[-1]['cmd'].append('bordercolor=%s' %
+ self._color_name_to_rgb(value))
elif element == 'textcolor':
value = self._get_value(line)
if value != '':
- self.layers[-1]['cmd'].append('textcolor=%s' % self._color_name_to_rgb(value))
+ self.layers[-1]['cmd'].append('textcolor=%s' %
+ self._color_name_to_rgb(value))
elif element in ('gridsize',
'gridorigin'):
@@ -1539,17 +1725,17 @@
value = self._get_value(line)
if value != '':
self.layers[-1]['cmd'].append('%s=%s' % (element, value))
-
+
elif element == 'griddraw':
value = self._get_value(line)
if value == '0':
self.layers[-1]['cmd'].append('-n')
-
+
elif element == 'gridgeo':
value = self._get_value(line)
if value == '1':
self.layers[-1]['cmd'].append('-g')
-
+
elif element == 'borderdraw':
value = self._get_value(line)
if value == '0':
@@ -1559,7 +1745,7 @@
value = self._get_value(line)
if value == '0':
self.layers[-1]['cmd'].append('-t')
-
+
else:
self.error += _(' row %d:') % line_id + line + os.linesep
self.num_error += 1
Modified: grass/trunk/gui/wxpython/core/ws.py
===================================================================
--- grass/trunk/gui/wxpython/core/ws.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/core/ws.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,15 +27,15 @@
from grass.script import core as grass
from grass.exceptions import CalledModuleError
-from core import utils
-from core.debug import Debug
-from core.gthread import gThread
+from core import utils
+from core.debug import Debug
+from core.gthread import gThread
from core.utils import _
try:
haveGdal = True
from osgeo import gdal
- from osgeo import gdalconst
+ from osgeo import gdalconst
except ImportError:
haveGdal = False
@@ -45,13 +45,14 @@
class RenderWMSMgr(wx.EvtHandler):
"""Fetch and prepare WMS data for rendering.
"""
+
def __init__(self, layer, env):
if not haveGdal:
- sys.stderr.write(_("Unable to load GDAL Python bindings.\n"\
+ sys.stderr.write(_("Unable to load GDAL Python bindings.\n"
"WMS layers can not be displayed without the bindings.\n"))
self.layer = layer
-
+
wx.EvtHandler.__init__(self)
# thread for d.wms commands
@@ -65,7 +66,7 @@
self.tempMap = grass.tempfile()
self.dstSize = {}
-
+
self.dataFetched = Signal('RenderWMSMgr.dataFetched')
self.updateProgress = Signal('RenderWMSMgr.updateProgress')
@@ -82,7 +83,7 @@
if not haveGdal:
return
- Debug.msg(1, "RenderWMSMgr.Render(%s): force=%d img=%s" % \
+ Debug.msg(1, "RenderWMSMgr.Render(%s): force=%d img=%s" %
(self.layer, self.layer.forceRender, self.layer.mapfile))
env = copy.copy(env)
@@ -93,7 +94,7 @@
self._fitAspect(region, self.dstSize)
self.updateMap = True
- fetchData = True # changed to True when calling Render()
+ fetchData = True # changed to True when calling Render()
zoomChanged = False
if self.renderedRegion is None or \
@@ -108,7 +109,7 @@
for c in ['e-w resol', 'n-s resol']:
if self.renderedRegion and \
- region[c] != self.renderedRegion[c]:
+ region[c] != self.renderedRegion[c]:
zoomChanged = True
break
@@ -120,7 +121,7 @@
try_remove(self.tempMap)
self.currentPid = self.thread.GetId()
- ### self.thread.Terminate()
+ # self.thread.Terminate()
self.downloading = True
self.fetching_cmd = cmd
@@ -129,15 +130,15 @@
env["GRASS_REGION"] = self._createRegionStr(region)
cmd_render = copy.deepcopy(cmd)
- cmd_render[1]['quiet'] = True # be quiet
-
+ cmd_render[1]['quiet'] = True # be quiet
+
self._startTime = time.time()
self.thread.Run(callable=self._render, cmd=cmd_render, env=env,
ondone=self.OnRenderDone)
self.layer.forceRender = False
-
+
self.updateProgress.emit(layer=self.layer)
-
+
def _render(self, cmd, env):
try:
return grass.run_command(cmd[0], env=env, **cmd[1])
@@ -157,23 +158,30 @@
self.fetched_data_cmd = None
return
- self.mapMerger = GDALRasterMerger(targetFile = self.layer.mapfile,
- region = self.renderedRegion,
- bandsNum = 3, gdalDriver = 'PNM', fillValue = 0)
- self.mapMerger.AddRasterBands(self.tempMap, {1 : 1, 2 : 2, 3 : 3})
+ self.mapMerger = GDALRasterMerger(
+ targetFile=self.layer.mapfile,
+ region=self.renderedRegion,
+ bandsNum=3,
+ gdalDriver='PNM',
+ fillValue=0)
+ self.mapMerger.AddRasterBands(self.tempMap, {1: 1, 2: 2, 3: 3})
del self.mapMerger
- self.maskMerger = GDALRasterMerger(targetFile = self.layer.maskfile, region = self.renderedRegion,
- bandsNum = 1, gdalDriver = 'PNM', fillValue = 0)
+ self.maskMerger = GDALRasterMerger(
+ targetFile=self.layer.maskfile,
+ region=self.renderedRegion,
+ bandsNum=1,
+ gdalDriver='PNM',
+ fillValue=0)
#{4 : 1} alpha channel (4) to first and only channel (1) in mask
- self.maskMerger.AddRasterBands(self.tempMap, {4 : 1})
+ self.maskMerger.AddRasterBands(self.tempMap, {4: 1})
del self.maskMerger
self.fetched_data_cmd = self.fetching_cmd
- Debug.msg(1, "RenderWMSMgr.OnRenderDone(%s): ret=%d time=%f" % \
- (self.layer, event.ret, time.time() - self._startTime))
-
+ Debug.msg(1, "RenderWMSMgr.OnRenderDone(%s): ret=%d time=%f" %
+ (self.layer, event.ret, time.time() - self._startTime))
+
self.dataFetched.emit(layer=self.layer)
def _getRegionDict(self, env):
@@ -209,7 +217,7 @@
return regionStr
def IsDownloading(self):
- """Is it downloading any data from WMS server?
+ """Is it downloading any data from WMS server?
"""
return self.downloading
@@ -219,7 +227,7 @@
if region['n-s resol'] > region['e-w resol']:
delta = region['n-s resol'] * size['cols'] / 2
- center = (region['east'] - region['west'])/2
+ center = (region['east'] - region['west']) / 2
region['east'] = center + delta + region['west']
region['west'] = center - delta + region['west']
@@ -228,7 +236,7 @@
else:
delta = region['e-w resol'] * size['rows'] / 2
- center = (region['north'] - region['south'])/2
+ center = (region['north'] - region['south']) / 2
region['north'] = center + delta + region['south']
region['south'] = center - delta + region['south']
@@ -238,18 +246,21 @@
"""Abort rendering process"""
Debug.msg(1, "RenderWMSMgr({}).Abort()".format(self.layer))
self.thread.Terminate()
-
+
# force rendering layer next time
self.layer.forceRender = True
self.updateMap = False
self.thread.Terminate(False)
+
class GDALRasterMerger:
"""Merge rasters.
Based on gdal_merge.py utility.
"""
- def __init__(self, targetFile, region, bandsNum, gdalDriver, fillValue = None):
+
+ def __init__(self, targetFile, region, bandsNum,
+ gdalDriver, fillValue=None):
"""Create raster for merging.
"""
self.gdalDrvType = gdalDriver
@@ -257,12 +268,19 @@
nsRes = (region['south'] - region['north']) / region['rows']
ewRes = (region['east'] - region['west']) / region['cols']
- self.tGeotransform = [region['west'], ewRes, 0, region['north'], 0, nsRes]
+ self.tGeotransform = [
+ region['west'],
+ ewRes, 0, region['north'],
+ 0, nsRes]
- self.tUlx, self.tUly, self.tLrx, self.tLry = self._getCorners(self.tGeotransform, region)
+ self.tUlx, self.tUly, self.tLrx, self.tLry = self._getCorners(
+ self.tGeotransform, region)
driver = gdal.GetDriverByName(self.gdalDrvType)
- self.tDataset = driver.Create(targetFile, region['cols'], region['rows'], bandsNum, gdal.GDT_Byte)
+ self.tDataset = driver.Create(
+ targetFile, region['cols'],
+ region['rows'],
+ bandsNum, gdal.GDT_Byte)
if fillValue is not None:
# fill raster bands with a constant value
@@ -272,29 +290,29 @@
def AddRasterBands(self, sourceFile, sTBands):
"""Add raster bands from sourceFile into the merging raster.
"""
- sDataset = gdal.Open(sourceFile, gdal.GA_ReadOnly)
+ sDataset = gdal.Open(sourceFile, gdal.GA_ReadOnly)
if sDataset is None:
return
sGeotransform = sDataset.GetGeoTransform()
sSize = {
- 'rows' : sDataset.RasterYSize,
- 'cols' : sDataset.RasterXSize
- }
+ 'rows': sDataset.RasterYSize,
+ 'cols': sDataset.RasterXSize
+ }
sUlx, sUly, sLrx, sLry = self._getCorners(sGeotransform, sSize)
# figure out intersection region
- tIntsctUlx = max(self.tUlx,sUlx)
- tIntsctLrx = min(self.tLrx,sLrx)
+ tIntsctUlx = max(self.tUlx, sUlx)
+ tIntsctLrx = min(self.tLrx, sLrx)
if self.tGeotransform[5] < 0:
- tIntsctUly = min(self.tUly,sUly)
- tIntsctLry = max(self.tLry,sLry)
+ tIntsctUly = min(self.tUly, sUly)
+ tIntsctLry = max(self.tLry, sLry)
else:
- tIntsctUly = max(self.tUly,sUly)
- tIntsctLry = min(self.tLry,sLry)
-
+ tIntsctUly = max(self.tUly, sUly)
+ tIntsctLry = min(self.tLry, sLry)
+
# do they even intersect?
if tIntsctUlx >= tIntsctLrx:
return
@@ -303,12 +321,21 @@
if self.tGeotransform[5] > 0 and tIntsctUly >= tIntsctLry:
return
-
# compute target window in pixel coordinates.
- tXoff = int((tIntsctUlx - self.tGeotransform[0]) / self.tGeotransform[1] + 0.1)
- tYoff = int((tIntsctUly - self.tGeotransform[3]) / self.tGeotransform[5] + 0.1)
- tXsize = int((tIntsctLrx - self.tGeotransform[0])/self.tGeotransform[1] + 0.5) - tXoff
- tYsize = int((tIntsctLry - self.tGeotransform[3])/self.tGeotransform[5] + 0.5) - tYoff
+ tXoff = int(
+ (tIntsctUlx -
+ self.tGeotransform[0]) /
+ self.tGeotransform[1] +
+ 0.1)
+ tYoff = int(
+ (tIntsctUly -
+ self.tGeotransform[3]) /
+ self.tGeotransform[5] +
+ 0.1)
+ tXsize = int(
+ (tIntsctLrx - self.tGeotransform[0]) / self.tGeotransform[1] + 0.5) - tXoff
+ tYsize = int(
+ (tIntsctLry - self.tGeotransform[3]) / self.tGeotransform[5] + 0.5) - tYoff
if tXsize < 1 or tYsize < 1:
return
@@ -316,17 +343,19 @@
# Compute source window in pixel coordinates.
sXoff = int((tIntsctUlx - sGeotransform[0]) / sGeotransform[1])
sYoff = int((tIntsctUly - sGeotransform[3]) / sGeotransform[5])
- sXsize = int((tIntsctLrx - sGeotransform[0]) / sGeotransform[1] + 0.5) - sXoff
- sYsize = int((tIntsctLry - sGeotransform[3]) / sGeotransform[5] + 0.5) - sYoff
+ sXsize = int(
+ (tIntsctLrx - sGeotransform[0]) / sGeotransform[1] + 0.5) - sXoff
+ sYsize = int(
+ (tIntsctLry - sGeotransform[3]) / sGeotransform[5] + 0.5) - sYoff
if sXsize < 1 or sYsize < 1:
return
for sBandNnum, tBandNum in sTBands.iteritems():
- bandData = sDataset.GetRasterBand(sBandNnum).ReadRaster(sXoff, sYoff, sXsize,
- sYsize, tXsize, tYsize, gdal.GDT_Byte)
- self.tDataset.GetRasterBand(tBandNum).WriteRaster(tXoff, tYoff, tXsize, tYsize, bandData,
- tXsize, tYsize, gdal.GDT_Byte)
+ bandData = sDataset.GetRasterBand(sBandNnum).ReadRaster(
+ sXoff, sYoff, sXsize, sYsize, tXsize, tYsize, gdal.GDT_Byte)
+ self.tDataset.GetRasterBand(tBandNum).WriteRaster(
+ tXoff, tYoff, tXsize, tYsize, bandData, tXsize, tYsize, gdal.GDT_Byte)
def _getCorners(self, geoTrans, size):
@@ -335,13 +364,13 @@
lrx = geoTrans[0] + size['cols'] * geoTrans[1]
lry = geoTrans[3] + size['rows'] * geoTrans[5]
- return ulx, uly, lrx, lry
+ return ulx, uly, lrx, lry
def SetGeorefAndProj(self):
"""Set georeference and projection to target file
"""
- projection = grass.read_command('g.proj',
- flags = 'wf')
+ projection = grass.read_command('g.proj',
+ flags='wf')
self.tDataset.SetProjection(projection)
self.tDataset.SetGeoTransform(self.tGeotransform)
Modified: grass/trunk/gui/wxpython/datacatalog/catalog.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/catalog.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/catalog.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,21 +25,23 @@
from grass.pydispatch.signal import Signal
+
class DataCatalog(wx.Panel):
"""Data catalog panel"""
- def __init__(self, parent, giface=None, id = wx.ID_ANY, title=_("Data catalog"),
- name='catalog', **kwargs):
+
+ def __init__(self, parent, giface=None, id=wx.ID_ANY,
+ title=_("Data catalog"), name='catalog', **kwargs):
"""Panel constructor """
self.showNotification = Signal('DataCatalog.showNotification')
self.parent = parent
self.baseTitle = title
- wx.Panel.__init__(self, parent = parent, id = id, **kwargs)
+ wx.Panel.__init__(self, parent=parent, id=id, **kwargs)
self.SetName("DataCatalog")
-
+
Debug.msg(1, "DataCatalog.__init__()")
# toolbar
- self.toolbar = DataCatalogToolbar(parent = self)
+ self.toolbar = DataCatalogToolbar(parent=self)
# tree with layers
self.tree = DataCatalogTree(self, giface=giface)
@@ -54,15 +56,15 @@
"""Do layout"""
sizer = wx.BoxSizer(wx.VERTICAL)
- sizer.Add(item = self.toolbar, proportion = 0,
- flag = wx.EXPAND)
+ sizer.Add(item=self.toolbar, proportion=0,
+ flag=wx.EXPAND)
- sizer.Add(item = self.tree.GetControl(), proportion = 1,
- flag = wx.EXPAND)
-
+ sizer.Add(item=self.tree.GetControl(), proportion=1,
+ flag=wx.EXPAND)
+
self.SetAutoLayout(True)
self.SetSizer(sizer)
-
+
self.Layout()
def LoadItems(self):
Modified: grass/trunk/gui/wxpython/datacatalog/frame.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/frame.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/frame.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -29,11 +29,17 @@
class DataCatalogFrame(wx.Frame):
"""Frame for testing purposes only."""
+
def __init__(self, parent, giface=None):
wx.Frame.__init__(self, parent=parent,
title=_('GRASS GIS Data Catalog'))
self.SetName("DataCatalog")
- self.SetIcon(wx.Icon(os.path.join(ICONDIR, 'grass.ico'), wx.BITMAP_TYPE_ICO))
+ self.SetIcon(
+ wx.Icon(
+ os.path.join(
+ ICONDIR,
+ 'grass.ico'),
+ wx.BITMAP_TYPE_ICO))
self._giface = giface
self.panel = wx.Panel(self)
Modified: grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/g.gui.datacatalog.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -27,16 +27,17 @@
import grass.script as gscript
+
def main():
options, flags = gscript.parser()
# import wx only after running parser
# to avoid issues when only interface is needed
import wx
-
+
from grass.script.setup import set_gui_path
set_gui_path()
-
+
from core.giface import StandaloneGrassInterface
from datacatalog.frame import DataCatalogFrame
Modified: grass/trunk/gui/wxpython/datacatalog/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/toolbars.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/toolbars.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,16 +20,25 @@
from core.utils import _
icons = {
- 'reloadTree': MetaIcon(img='redraw', label=_("Reload GRASS locations")),
- 'reloadMapset': MetaIcon(img='reload', label=_("Reload current GRASS mapset only")),
- 'unlocked': MetaIcon(img='unlocked', label=_("Click to restrict editing to current mapset only")),
- 'locked': MetaIcon(img='locked', label=_("Click to allow editing other mapsets")),
- }
+ 'reloadTree': MetaIcon(
+ img='redraw',
+ label=_("Reload GRASS locations")),
+ 'reloadMapset': MetaIcon(
+ img='reload',
+ label=_("Reload current GRASS mapset only")),
+ 'unlocked': MetaIcon(
+ img='unlocked',
+ label=_("Click to restrict editing to current mapset only")),
+ 'locked': MetaIcon(
+ img='locked',
+ label=_("Click to allow editing other mapsets")),
+}
class DataCatalogToolbar(BaseToolbar):
"""Main data catalog toolbar
"""
+
def __init__(self, parent):
"""Main toolbar constructor
"""
Modified: grass/trunk/gui/wxpython/datacatalog/tree.py
===================================================================
--- grass/trunk/gui/wxpython/datacatalog/tree.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/datacatalog/tree.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -61,29 +61,46 @@
elements = ['raster', 'raster_3d', 'vector']
try:
if not mapsets:
- mapsets = gscript.read_command('g.mapsets', flags='l', separator='comma', quiet=True, env=env).strip()
+ mapsets = gscript.read_command(
+ 'g.mapsets',
+ flags='l',
+ separator='comma',
+ quiet=True,
+ env=env).strip()
except CalledModuleError:
- queue.put((maps_dict, _("Failed to read mapsets from location <{l}>.").format(l=location)))
+ queue.put(
+ (maps_dict,
+ _("Failed to read mapsets from location <{l}>.").format(
+ l=location)))
gscript.try_remove(tmp_gisrc_file)
return
else:
listOfMapsets = mapsets.split(',')
- Debug.msg(4, "Location <{}>: {} mapsets found".format(location, len(listOfMapsets)))
+ Debug.msg(
+ 4, "Location <{}>: {} mapsets found".format(
+ location, len(listOfMapsets)))
for each in listOfMapsets:
maps_dict[each] = {}
for elem in elements:
maps_dict[each][elem] = []
try:
- maplist = gscript.read_command('g.list', flags='mt', type=elements,
- mapset=','.join(listOfMapsets), quiet=True, env=env).strip()
+ maplist = gscript.read_command(
+ 'g.list', flags='mt', type=elements,
+ mapset=','.join(listOfMapsets),
+ quiet=True, env=env).strip()
except CalledModuleError:
- queue.put((maps_dict, _("Failed to read maps from location <{l}>.").format(l=location)))
+ queue.put(
+ (maps_dict,
+ _("Failed to read maps from location <{l}>.").format(
+ l=location)))
gscript.try_remove(tmp_gisrc_file)
return
else:
# fill dictionary
listOfMaps = maplist.splitlines()
- Debug.msg(4, "Location <{}>: {} maps found".format(location, len(listOfMaps)))
+ Debug.msg(
+ 4, "Location <{}>: {} maps found".format(
+ location, len(listOfMaps)))
for each in listOfMaps:
ltype, wholename = each.split('/')
name, mapset = wholename.split('@')
@@ -109,9 +126,15 @@
element = 'grid3'
# g.findfile returns non-zero when file was not found
# se we ignore return code and just focus on stdout
- process = gscript.start_command('g.findfile', flags='n',
- element=element, file=name, mapset=mapset,
- stdout=gscript.PIPE, stderr=gscript.PIPE, env=env)
+ process = gscript.start_command(
+ 'g.findfile',
+ flags='n',
+ element=element,
+ file=name,
+ mapset=mapset,
+ stdout=gscript.PIPE,
+ stderr=gscript.PIPE,
+ env=env)
output, errors = process.communicate()
info = gscript.parse_key_val(output, sep='=')
# file is the key questioned in grass.script.core find_file()
@@ -123,6 +146,7 @@
class NameEntryDialog(TextEntryDialog):
+
def __init__(self, element, mapset, env, **kwargs):
TextEntryDialog.__init__(self, **kwargs)
self._element = element
@@ -136,10 +160,16 @@
if not new:
return
if map_exists(new, self._element, self._env, self._mapset):
- dlg = wx.MessageDialog(self, message=_("Map of type {elem} <{name}> already exists in mapset <{mapset}>. "
- "Do you want to overwrite it?").format(elem=self._element,
- name=new, mapset=self._mapset),
- caption=_("Overwrite?"), style=wx.YES_NO)
+ dlg = wx.MessageDialog(
+ self,
+ message=_(
+ "Map of type {elem} <{name}> already exists in mapset <{mapset}>. "
+ "Do you want to overwrite it?").format(
+ elem=self._element,
+ name=new,
+ mapset=self._mapset),
+ caption=_("Overwrite?"),
+ style=wx.YES_NO)
if dlg.ShowModal() == wx.ID_YES:
dlg.Destroy()
self._env['GRASS_OVERWRITE'] = '1'
@@ -153,6 +183,7 @@
class DataCatalogNode(DictNode):
"""Node representing item in datacatalog."""
+
def __init__(self, label, data=None):
super(DataCatalogNode, self).__init__(label=label, data=data)
@@ -172,11 +203,20 @@
class LocationMapTree(TreeView):
- def __init__(self, parent, model=None, style=wx.TR_HIDE_ROOT | wx.TR_EDIT_LABELS | wx.TR_LINES_AT_ROOT |
- wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT | wx.TR_SINGLE):
+
+ def __init__(
+ self, parent, model=None, style=wx.TR_HIDE_ROOT | wx.TR_EDIT_LABELS
+ | wx.TR_LINES_AT_ROOT | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT |
+ wx.TR_SINGLE):
"""Location Map Tree constructor."""
self._model = TreeModel(DataCatalogNode)
- super(LocationMapTree, self).__init__(parent=parent, model=self._model, id=wx.ID_ANY, style=style)
+ super(
+ LocationMapTree,
+ self).__init__(
+ parent=parent,
+ model=self._model,
+ id=wx.ID_ANY,
+ style=style)
self.showNotification = Signal('Tree.showNotification')
self.parent = parent
self.contextMenu.connect(self.OnRightClick)
@@ -200,23 +240,26 @@
try:
nprocs = cpu_count()
except NotImplementedError:
- nprocs = 4
+ nprocs = 4
results = dict()
errors = []
location_nodes = []
nlocations = len(locations)
- grassdata_node = self._model.AppendNode(parent=self._model.root,
- label=_('GRASS locations in {}').format(genv['GISDBASE']),
- data=dict(type='grassdata'))
+ grassdata_node = self._model.AppendNode(
+ parent=self._model.root, label=_('GRASS locations in {}').format(
+ genv['GISDBASE']), data=dict(
+ type='grassdata'))
for location in locations:
results[location] = dict()
- varloc = self._model.AppendNode(parent=grassdata_node, label=location,
- data=dict(type='location', name=location))
+ varloc = self._model.AppendNode(
+ parent=grassdata_node, label=location, data=dict(
+ type='location', name=location))
location_nodes.append(varloc)
loc_count += 1
- Debug.msg(3, "Scanning location <{}> ({}/{})".format(location, loc_count, nlocations))
+ Debug.msg(
+ 3, "Scanning location <{}> ({}/{})".format(location, loc_count, nlocations))
q = Queue()
p = Process(target=getLocationTree,
@@ -238,8 +281,10 @@
errors.append(error)
for key in sorted(maps.keys()):
- mapset_node = self._model.AppendNode(parent=location_nodes[i], label=key,
- data=dict(type='mapset', name=key))
+ mapset_node = self._model.AppendNode(
+ parent=location_nodes[i],
+ label=key, data=dict(
+ type='mapset', name=key))
self._populateMapsetItem(mapset_node, maps[key])
proc_count = 0
@@ -284,8 +329,13 @@
node = get_first_child(mapsetItem)
q = Queue()
- p = Process(target=getLocationTree,
- args=(genv['GISDBASE'], locationItem.data['name'], q, mapsetItem.data['name']))
+ p = Process(
+ target=getLocationTree,
+ args=(
+ genv['GISDBASE'],
+ locationItem.data['name'],
+ q,
+ mapsetItem.data['name']))
p.start()
maps, error = q.get()
if error:
@@ -298,8 +348,9 @@
def _populateMapsetItem(self, mapset_node, data):
for elem in data:
if data[elem]:
- element_node = self._model.AppendNode(parent=mapset_node, label=elem,
- data=dict(type='element', name=elem))
+ element_node = self._model.AppendNode(
+ parent=mapset_node, label=elem,
+ data=dict(type='element', name=elem))
for layer in data[elem]:
self._model.AppendNode(parent=element_node, label=layer,
data=dict(type=elem, name=layer))
@@ -392,7 +443,9 @@
if not locationItem:
return None, None
- mapsetItem = self._model.SearchNodes(parent=locationItem[0], name=mapset, type='mapset')
+ mapsetItem = self._model.SearchNodes(
+ parent=locationItem[0],
+ name=mapset, type='mapset')
if not mapsetItem:
return locationItem[0], None
@@ -407,6 +460,7 @@
class DataCatalogTree(LocationMapTree):
+
def __init__(self, parent, giface=None):
"""Data Catalog Tree constructor."""
super(DataCatalogTree, self).__init__(parent)
@@ -459,17 +513,27 @@
self.copy_type = self.selected_type
self.copy_mapset = self.selected_mapset
self.copy_location = self.selected_location
- label = _("Map <{layer}> marked for copying. "
- "You can paste it to the current mapset "
- "<{mapset}>.".format(layer=self.copy_layer.label, mapset=gisenv()['MAPSET']))
+ label = _(
+ "Map <{layer}> marked for copying. "
+ "You can paste it to the current mapset "
+ "<{mapset}>.".format(
+ layer=self.copy_layer.label,
+ mapset=gisenv()['MAPSET']))
self.showNotification.emit(message=label)
def OnRenameMap(self, event):
"""Rename layer with dialog"""
old_name = self.selected_layer.label
- gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
- new_name = self._getNewMapName(_('New name'), _('Rename map'),
- old_name, env=env, mapset=self.selected_mapset.label, element=self.selected_type.label)
+ gisrc, env = getEnvironment(
+ gisenv()['GISDBASE'],
+ self.selected_location.label, mapset=self.selected_mapset.label)
+ new_name = self._getNewMapName(
+ _('New name'),
+ _('Rename map'),
+ old_name,
+ env=env,
+ mapset=self.selected_mapset.label,
+ element=self.selected_type.label)
if new_name:
self.Rename(old_name, new_name)
@@ -493,7 +557,9 @@
def Rename(self, old, new):
"""Rename layer"""
string = old + ',' + new
- gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, self.selected_mapset.label)
+ gisrc, env = getEnvironment(
+ gisenv()['GISDBASE'],
+ self.selected_location.label, self.selected_mapset.label)
label = _("Renaming map <{name}>...").format(name=string)
self.showNotification.emit(message=label)
if self.selected_type.label == 'vector':
@@ -501,12 +567,14 @@
elif self.selected_type.label == 'raster':
renamed, cmd = self._runCommand('g.rename', raster=string, env=env)
else:
- renamed, cmd = self._runCommand('g.rename', raster3d=string, env=env)
+ renamed, cmd = self._runCommand(
+ 'g.rename', raster3d=string, env=env)
if renamed == 0:
self.selected_layer.label = new
self.selected_layer.data['name'] = new
self.RefreshNode(self.selected_layer)
- self.showNotification.emit(message=_("{cmd} -- completed").format(cmd=cmd))
+ self.showNotification.emit(
+ message=_("{cmd} -- completed").format(cmd=cmd))
Debug.msg(1, "LAYER RENAMED TO: " + new)
gscript.try_remove(gisrc)
@@ -517,29 +585,47 @@
GMessage(_("No map selected for copying."), parent=self)
return
if self.selected_location == self.copy_location:
- gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
- new_name = self._getNewMapName(_('New name'), _('Copy map'),
- self.copy_layer.label, env=env, mapset=self.selected_mapset.label, element=self.copy_type.label)
+ gisrc, env = getEnvironment(
+ gisenv()['GISDBASE'], self.selected_location.label, mapset=self.selected_mapset.label)
+ new_name = self._getNewMapName(
+ _('New name'),
+ _('Copy map'),
+ self.copy_layer.label,
+ env=env,
+ mapset=self.selected_mapset.label,
+ element=self.copy_type.label)
if not new_name:
return
- if map_exists(new_name, element=self.copy_type.label, env=env, mapset=self.selected_mapset.label):
- GMessage(_("Failed to copy map: new map has the same name"), parent=self)
+ if map_exists(
+ new_name, element=self.copy_type.label, env=env,
+ mapset=self.selected_mapset.label):
+ GMessage(
+ _("Failed to copy map: new map has the same name"),
+ parent=self)
return
if not self.selected_type:
- found = self._model.SearchNodes(parent=self.selected_mapset, type='element', name=self.copy_type.label)
+ found = self._model.SearchNodes(
+ parent=self.selected_mapset, type='element',
+ name=self.copy_type.label)
self.selected_type = found[0] if found else None
overwrite = False
if self.selected_type:
- found = self._model.SearchNodes(parent=self.selected_type, type=self.copy_type.label, name=new_name)
+ found = self._model.SearchNodes(
+ parent=self.selected_type,
+ type=self.copy_type.label,
+ name=new_name)
if found and found[0]:
- dlg = wx.MessageDialog(parent=self,
- message=_("Map <{map}> already exists "
- "in the current mapset. "
- "Do you want to overwrite it?").format(map=new_name),
- caption=_("Overwrite?"),
- style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+ dlg = wx.MessageDialog(
+ parent=self,
+ message=_(
+ "Map <{map}> already exists "
+ "in the current mapset. "
+ "Do you want to overwrite it?").format(
+ map=new_name),
+ caption=_("Overwrite?"),
+ style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
ret = dlg.ShowModal()
dlg.Destroy()
if ret == wx.ID_YES:
@@ -551,34 +637,44 @@
label = _("Copying <{name}>...").format(name=string)
self.showNotification.emit(message=label)
if self.copy_type.label == 'vector':
- pasted, cmd = self._runCommand('g.copy', vector=string, overwrite=overwrite, env=env)
+ pasted, cmd = self._runCommand(
+ 'g.copy', vector=string, overwrite=overwrite, env=env)
node = 'vector'
elif self.copy_type.label == 'raster':
- pasted, cmd = self._runCommand('g.copy', raster=string, overwrite=overwrite, env=env)
+ pasted, cmd = self._runCommand(
+ 'g.copy', raster=string, overwrite=overwrite, env=env)
node = 'raster'
else:
- pasted, cmd = self._runCommand('g.copy', raster_3d=string, overwrite=overwrite, env=env)
+ pasted, cmd = self._runCommand(
+ 'g.copy', raster_3d=string, overwrite=overwrite, env=env)
node = 'raster_3d'
if pasted == 0:
- self.InsertLayer(name=new_name, mapset_node=self.selected_mapset, element_name=node)
+ self.InsertLayer(
+ name=new_name,
+ mapset_node=self.selected_mapset,
+ element_name=node)
Debug.msg(1, "COPIED TO: " + new_name)
- self.showNotification.emit(message=_("g.copy completed").format(cmd=cmd))
+ self.showNotification.emit(
+ message=_("g.copy completed").format(cmd=cmd))
gscript.try_remove(gisrc)
else:
- GError(_("Failed to copy map: action is allowed only within the same location."),
- parent=self)
+ GError(
+ _("Failed to copy map: action is allowed only within the same location."),
+ parent=self)
# expand selected mapset
self.ExpandNode(self.selected_mapset, recursive=True)
def InsertLayer(self, name, mapset_node, element_name):
"""Insert layer into model and refresh tree"""
- found_element = self._model.SearchNodes(parent=mapset_node, type='element', name=element_name)
+ found_element = self._model.SearchNodes(
+ parent=mapset_node, type='element', name=element_name)
found_element = found_element[0] if found_element else None
if not found_element:
# add type node if not exists
- found_element = self._model.AppendNode(parent=mapset_node, label=element_name,
- data=dict(type='element', name=element_name))
+ found_element = self._model.AppendNode(
+ parent=mapset_node, label=element_name,
+ data=dict(type='element', name=element_name))
found = self._model.SearchNodes(parent=found_element, name=name)
if len(found) == 0:
self._model.AppendNode(parent=found_element, label=name,
@@ -589,34 +685,41 @@
def OnDeleteMap(self, event):
"""Delete layer or mapset"""
name = self.selected_layer.label
- gisrc, env = getEnvironment(gisenv()['GISDBASE'], self.selected_location.label, self.selected_mapset.label)
- if self._confirmDialog(question=_("Do you really want to delete map <{m}> of type <{etype}> from mapset "
- "<{mapset}> in location <{loc}>?").format(m=name, mapset=self.selected_mapset.label,
- etype=self.selected_type.label,
- loc=self.selected_location.label),
- title=_('Delete map')) == wx.ID_YES:
+ gisrc, env = getEnvironment(
+ gisenv()['GISDBASE'],
+ self.selected_location.label, self.selected_mapset.label)
+ if self._confirmDialog(
+ question=_(
+ "Do you really want to delete map <{m}> of type <{etype}> from mapset "
+ "<{mapset}> in location <{loc}>?").format(
+ m=name, mapset=self.selected_mapset.label,
+ etype=self.selected_type.label,
+ loc=self.selected_location.label),
+ title=_('Delete map')) == wx.ID_YES:
label = _("Deleting {name}...").format(name=name)
self.showNotification.emit(message=label)
if self.selected_type.label == 'vector':
- removed, cmd = self._runCommand('g.remove', flags='f', type='vector',
- name=name, env=env)
+ removed, cmd = self._runCommand(
+ 'g.remove', flags='f', type='vector', name=name, env=env)
elif self.selected_type.label == 'raster':
- removed, cmd = self._runCommand('g.remove', flags='f', type='raster',
- name=name, env=env)
+ removed, cmd = self._runCommand(
+ 'g.remove', flags='f', type='raster', name=name, env=env)
else:
- removed, cmd = self._runCommand('g.remove', flags='f', type='raster_3d',
- name=name, env=env)
+ removed, cmd = self._runCommand(
+ 'g.remove', flags='f', type='raster_3d', name=name, env=env)
if removed == 0:
self._model.RemoveNode(self.selected_layer)
self.RefreshNode(self.selected_type, recursive=True)
Debug.msg(1, "LAYER " + name + " DELETED")
- self.showNotification.emit(message=_("g.remove completed").format(cmd=cmd))
+ self.showNotification.emit(
+ message=_("g.remove completed").format(cmd=cmd))
gscript.try_remove(gisrc)
def OnDisplayLayer(self, event):
"""Display layer in current graphics view"""
layerName = []
- if self.selected_location.label == gisenv()['LOCATION_NAME'] and self.selected_mapset:
+ if self.selected_location.label == gisenv(
+ )['LOCATION_NAME'] and self.selected_mapset:
string = self.selected_layer.label + '@' + self.selected_mapset.label
layerName.append(string)
label = _("Displaying {name}...").format(name=string)
@@ -629,18 +732,21 @@
self._giface.lmgr.AddMaps(layerName, 'raster', True)
else:
self._giface.lmgr.AddMaps(layerName, 'raster_3d', True)
- label = "d.rast --q map=" + string + _(" -- completed. Go to Layers tab for further operations.") # generate this message (command) automatically?
+ # generate this message (command) automatically?
+ label = "d.rast --q map=" + string + _(
+ " -- completed. Go to Layers tab for further operations.")
self.showNotification.emit(message=label)
Debug.msg(1, "LAYER " + self.selected_layer.label + " DISPLAYED")
else:
- GError(_("Failed to display layer: not in current mapset or invalid layer"),
- parent=self)
+ GError(
+ _("Failed to display layer: not in current mapset or invalid layer"),
+ parent=self)
def OnBeginDrag(self, node, event):
"""Just copy necessary data"""
self.DefineItems(node)
- if self.selected_layer and \
- not (self._restricted and gisenv()['LOCATION_NAME'] != self.selected_location.label):
+ if self.selected_layer and not (self._restricted and gisenv()[
+ 'LOCATION_NAME'] != self.selected_location.label):
event.Allow()
self.OnCopyMap(event)
Debug.msg(1, "DRAG")
@@ -656,8 +762,11 @@
return
if node:
self.DefineItems(node)
- if self._restricted and gisenv()['MAPSET'] != self.selected_mapset.label:
- GMessage(_("Maps can be copied only to current mapset"), parent=self)
+ if self._restricted and gisenv(
+ )['MAPSET'] != self.selected_mapset.label:
+ GMessage(
+ _("Maps can be copied only to current mapset"),
+ parent=self)
event.Veto()
return
if self.selected_location == self.copy_location and self.selected_mapset:
@@ -708,7 +817,9 @@
item = wx.MenuItem(menu, wx.NewId(), _("&Paste"))
menu.AppendItem(item)
self.Bind(wx.EVT_MENU, self.OnPasteMap, item)
- if not(currentLocation and self.copy_layer and self.selected_location == self.copy_location):
+ if not(
+ currentLocation and self.copy_layer and self.selected_location ==
+ self.copy_location):
item.Enable(False)
item = wx.MenuItem(menu, wx.NewId(), _("&Delete"))
Modified: grass/trunk/gui/wxpython/dbmgr/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/__init__.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/__init__.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -5,4 +5,4 @@
'manager',
'base',
'dialogs',
- ]
+]
Modified: grass/trunk/gui/wxpython/dbmgr/base.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/base.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/base.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -40,24 +40,26 @@
from core import globalvar
import wx
import wx.lib.mixins.listctrl as listmix
-import wx.lib.flatnotebook as FN
+import wx.lib.flatnotebook as FN
import wx.lib.scrolledpanel as scrolled
import grass.script as grass
from dbmgr.sqlbuilder import SQLBuilderSelect, SQLBuilderUpdate
-from core.gcmd import RunCommand, GException, GError, GMessage, GWarning
-from core.utils import ListOfCatsToRange, _
+from core.gcmd import RunCommand, GException, GError, GMessage, GWarning
+from core.utils import ListOfCatsToRange, _
from gui_core.dialogs import CreateNewVector
-from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue, CreateDbInfoDesc
-from core.debug import Debug
-from dbmgr.dialogs import ModifyTableRecord, AddColumnDialog
-from core.settings import UserSettings
+from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue, CreateDbInfoDesc
+from core.debug import Debug
+from dbmgr.dialogs import ModifyTableRecord, AddColumnDialog
+from core.settings import UserSettings
+
class Log:
"""The log output SQL is redirected to the status bar of the
containing frame.
"""
+
def __init__(self, parent):
self.parent = parent
@@ -66,66 +68,70 @@
if self.parent:
self.parent.SetStatusText(text_string.strip())
+
class VirtualAttributeList(wx.ListCtrl,
listmix.ListCtrlAutoWidthMixin,
listmix.ColumnSorterMixin):
"""Support virtual list class for Attribute Table Manager (browse page)
"""
+
def __init__(self, parent, log, dbMgrData, layer, pages):
# initialize variables
- self.parent = parent
- self.log = log
+ self.parent = parent
+ self.log = log
self.dbMgrData = dbMgrData
self.mapDBInfo = self.dbMgrData['mapDBInfo']
- self.layer = layer
+ self.layer = layer
self.pages = pages
self.fieldCalc = None
- self.fieldStats = None
- self.columns = {} # <- LoadData()
-
+ self.fieldStats = None
+ self.columns = {} # <- LoadData()
+
self.sqlFilter = {}
- wx.ListCtrl.__init__(self, parent = parent, id = wx.ID_ANY,
- style = wx.LC_REPORT | wx.LC_HRULES |
- wx.LC_VRULES | wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
-
+ wx.ListCtrl.__init__(self, parent=parent, id=wx.ID_ANY,
+ style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+ wx.LC_VIRTUAL | wx.LC_SORT_ASCENDING)
+
try:
keyColumn = self.LoadData(layer)
except GException as e:
- GError(parent = self,
- message = e.value)
+ GError(parent=self,
+ message=e.value)
return
-
+
# add some attributes (colourful background for each item rows)
self.attr1 = wx.ListItemAttr()
- self.attr1.SetBackgroundColour(wx.Colour(238,238,238))
+ self.attr1.SetBackgroundColour(wx.Colour(238, 238, 238))
self.attr2 = wx.ListItemAttr()
self.attr2.SetBackgroundColour("white")
self.il = wx.ImageList(16, 16)
- self.sm_up = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_UP, wx.ART_TOOLBAR,
- (16,16)))
- self.sm_dn = self.il.Add(wx.ArtProvider_GetBitmap(wx.ART_GO_DOWN, wx.ART_TOOLBAR,
- (16,16)))
+ self.sm_up = self.il.Add(
+ wx.ArtProvider_GetBitmap(
+ wx.ART_GO_UP, wx.ART_TOOLBAR, (16, 16)))
+ self.sm_dn = self.il.Add(
+ wx.ArtProvider_GetBitmap(
+ wx.ART_GO_DOWN, wx.ART_TOOLBAR, (16, 16)))
self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
-
+
# setup mixins
listmix.ListCtrlAutoWidthMixin.__init__(self)
listmix.ColumnSorterMixin.__init__(self, len(self.columns))
# sort item by category (id)
if keyColumn > -1:
- self.SortListItems(col = keyColumn, ascending = True)
+ self.SortListItems(col=keyColumn, ascending=True)
elif keyColumn:
- self.SortListItems(col = 0, ascending = True)
-
+ self.SortListItems(col=0, ascending=True)
+
# events
- self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
+ self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
self.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
- self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnSort)
- self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColumnMenu)
-
- def Update(self, mapDBInfo = None):
+ self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColumnSort)
+ self.Bind(wx.EVT_LIST_COL_RIGHT_CLICK, self.OnColumnMenu)
+
+ def Update(self, mapDBInfo=None):
"""Update list according new mapDBInfo description"""
if mapDBInfo:
self.mapDBInfo = mapDBInfo
@@ -133,46 +139,46 @@
else:
self.LoadData(self.layer, **self.sqlFilter)
- def LoadData(self, layer, columns = None, where = None, sql = None):
+ def LoadData(self, layer, columns=None, where=None, sql=None):
"""Load data into list
:param layer: layer number
:param columns: list of columns for output (-> v.db.select)
:param where: where statement (-> v.db.select)
:param sql: full sql statement (-> db.select)
-
- :return: id of key column
+
+ :return: id of key column
:return: -1 if key column is not displayed
"""
self.log.write(_("Loading data..."))
-
- tableName = self.mapDBInfo.layers[layer]['table']
- keyColumn = self.mapDBInfo.layers[layer]['key']
+
+ tableName = self.mapDBInfo.layers[layer]['table']
+ keyColumn = self.mapDBInfo.layers[layer]['key']
try:
self.columns = self.mapDBInfo.tables[tableName]
except KeyError:
raise GException(_("Attribute table <%s> not found. "
- "For creating the table switch to "
- "'Manage layers' tab.") % tableName)
-
+ "For creating the table switch to "
+ "'Manage layers' tab.") % tableName)
+
if not columns:
columns = self.mapDBInfo.GetColumns(tableName)
else:
all = self.mapDBInfo.GetColumns(tableName)
for col in columns:
if col not in all:
- GError(parent = self,
- message = _("Column <%(column)s> not found in "
- "in the table <%(table)s>.") % \
- { 'column' : col, 'table' : tableName })
+ GError(parent=self,
+ message=_("Column <%(column)s> not found in "
+ "in the table <%(table)s>.") %
+ {'column': col, 'table': tableName})
return
-
+
try:
# for maps connected via v.external
keyId = columns.index(keyColumn)
except:
keyId = -1
-
+
# read data
# FIXME: Max. number of rows, while the GUI is still usable
@@ -184,46 +190,46 @@
# highly unlikely to exist naturally.
fs = '{_sep_}'
- outFile = tempfile.NamedTemporaryFile(mode = 'w+b')
+ outFile = tempfile.NamedTemporaryFile(mode='w+b')
- cmdParams = dict(quiet = True,
- parent = self,
- flags = 'c',
- separator = fs)
+ cmdParams = dict(quiet=True,
+ parent=self,
+ flags='c',
+ separator=fs)
if sql:
- cmdParams.update(dict(sql = sql,
- output = outFile.name,
- overwrite = True))
+ cmdParams.update(dict(sql=sql,
+ output=outFile.name,
+ overwrite=True))
ret = RunCommand('db.select',
**cmdParams)
- self.sqlFilter = {"sql" : sql}
+ self.sqlFilter = {"sql": sql}
else:
- cmdParams.update(dict(map = self.mapDBInfo.map,
- layer = layer,
- where = where,
- stdout = outFile))
-
- self.sqlFilter = {"where" : where}
+ cmdParams.update(dict(map=self.mapDBInfo.map,
+ layer=layer,
+ where=where,
+ stdout=outFile))
+ self.sqlFilter = {"where": where}
+
if columns:
- cmdParams.update(dict(columns = ','.join(columns)))
+ cmdParams.update(dict(columns=','.join(columns)))
ret = RunCommand('v.db.select',
**cmdParams)
-
+
# These two should probably be passed to init more cleanly
# setting the numbers of items = number of elements in the dictionary
- self.itemDataMap = {}
+ self.itemDataMap = {}
self.itemIndexMap = []
- self.itemCatsMap = {}
-
+ self.itemCatsMap = {}
+
self.DeleteAllItems()
-
+
# self.ClearAll()
for i in range(self.GetColumnCount()):
self.DeleteColumn(0)
-
+
i = 0
info = wx.ListItem()
info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
@@ -233,18 +239,19 @@
info.m_text = column
self.InsertColumnInfo(i, info)
i += 1
-
+
if i >= 256:
self.log.write(_("Can display only 256 columns."))
-
+
i = 0
outFile.seek(0)
-
+
while True:
# os.linesep doesn't work here (MSYS)
# not sure what the replace is for?
# but we need strip to get rid of the ending newline
- # which on windows leaves \r in a last empty attribute table cell and causes error
+ # which on windows leaves \r in a last empty attribute table cell
+ # and causes error
record = outFile.readline().strip().replace('\n', '')
if not record:
@@ -252,64 +259,67 @@
record = record.split(fs)
if len(columns) != len(record):
- GError(parent = self,
- message = _("Inconsistent number of columns "
- "in the table <%(table)s>.") % \
- {'table' : tableName })
- self.columns = {} # because of IsEmpty method
+ GError(parent=self,
+ message=_("Inconsistent number of columns "
+ "in the table <%(table)s>.") %
+ {'table': tableName})
+ self.columns = {} # because of IsEmpty method
return
self.AddDataRow(i, record, columns, keyId)
-
+
i += 1
if i >= 100000:
self.log.write(_("Viewing limit: 100000 records."))
break
-
+
self.SetItemCount(i)
-
+
if where:
item = -1
while True:
item = self.GetNextItem(item)
if item == -1:
break
- self.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
-
+ self.SetItemState(
+ item,
+ wx.LIST_STATE_SELECTED,
+ wx.LIST_STATE_SELECTED)
+
i = 0
for col in columns:
- width = self.columns[col]['length'] * 6 # FIXME
+ width = self.columns[col]['length'] * 6 # FIXME
if width < 60:
width = 60
if width > 300:
width = 300
- self.SetColumnWidth(col = i, width = width)
+ self.SetColumnWidth(col=i, width=width)
i += 1
-
+
self.SendSizeEvent()
-
- self.log.write(_("Number of loaded records: %d") % \
- self.GetItemCount())
-
+
+ self.log.write(_("Number of loaded records: %d") %
+ self.GetItemCount())
+
return keyId
-
+
def AddDataRow(self, i, record, columns, keyId):
"""Add row to the data list"""
self.itemDataMap[i] = []
keyColumn = self.mapDBInfo.layers[self.layer]['key']
j = 0
cat = None
-
+
if keyColumn == 'OGC_FID':
- self.itemDataMap[i].append(i+1)
+ self.itemDataMap[i].append(i + 1)
j += 1
cat = i + 1
-
+
for value in record:
if self.columns[columns[j]]['ctype'] != types.StringType:
try:
- ### casting disabled (2009/03)
- ### self.itemDataMap[i].append(self.columns[columns[j]]['ctype'](value))
+ # casting disabled (2009/03)
+ # self.itemDataMap[i].append(self.columns[columns[j]]['ctype'](value))
self.itemDataMap[i].append(value)
except ValueError:
self.itemDataMap[i].append(_('Unknown value'))
@@ -320,32 +330,36 @@
except UnicodeDecodeError:
self.itemDataMap[i].append(_("Unable to decode value. "
"Set encoding in GUI preferences ('Attributes')."))
-
+
if not cat and keyId > -1 and keyId == j:
try:
- cat = self.columns[columns[j]]['ctype'] (value)
+ cat = self.columns[columns[j]]['ctype'](value)
except ValueError as e:
cat = -1
- GError(parent = self,
- message = _("Error loading attribute data. "
- "Record number: %(rec)d. Unable to convert value '%(val)s' in "
- "key column (%(key)s) to integer.\n\n"
- "Details: %(detail)s") % \
- { 'rec' : i + 1, 'val' : value,
- 'key' : keyColumn, 'detail' : e})
+ GError(
+ parent=self,
+ message=_(
+ "Error loading attribute data. "
+ "Record number: %(rec)d. Unable to convert value '%(val)s' in "
+ "key column (%(key)s) to integer.\n\n"
+ "Details: %(detail)s") % {
+ 'rec': i + 1,
+ 'val': value,
+ 'key': keyColumn,
+ 'detail': e})
j += 1
-
+
self.itemIndexMap.append(i)
- if keyId > -1: # load cats only when LoadData() is called first time
+ if keyId > -1: # load cats only when LoadData() is called first time
self.itemCatsMap[i] = cat
-
+
def OnItemSelected(self, event):
"""Item selected. Add item to selected cats..."""
# cat = int(self.GetItemText(event.m_itemIndex))
# if cat not in self.selectedCats:
# self.selectedCats.append(cat)
# self.selectedCats.sort()
-
+
event.Skip()
def OnItemDeselected(self, event):
@@ -372,7 +386,7 @@
cats = []
for item in range(self.GetItemCount()):
cats.append(self.GetItemText(item))
-
+
return cats
def GetColumnText(self, index, col):
@@ -392,7 +406,7 @@
def OnGetItemAttr(self, item):
"""Get item attributes"""
- if ( item % 2) == 0:
+ if (item % 2) == 0:
return self.attr2
else:
return self.attr1
@@ -400,70 +414,100 @@
def OnColumnMenu(self, event):
"""Column heading right mouse button -> pop-up menu"""
self._col = event.GetColumn()
-
+
popupMenu = wx.Menu()
- if not hasattr (self, "popupID"):
- self.popupId = { 'sortAsc' : wx.NewId(),
- 'sortDesc' : wx.NewId(),
- 'calculate' : wx.NewId(),
- 'area' : wx.NewId(),
- 'length' : wx.NewId(),
- 'compact' : wx.NewId(),
- 'fractal' : wx.NewId(),
- 'perimeter' : wx.NewId(),
- 'ncats' : wx.NewId(),
- 'slope' : wx.NewId(),
- 'lsin' : wx.NewId(),
- 'lazimuth' : wx.NewId(),
- 'calculator' : wx.NewId(),
- 'stats' : wx.NewId() }
-
- popupMenu.Append(self.popupId['sortAsc'], text = _("Sort ascending"))
- popupMenu.Append(self.popupId['sortDesc'], text = _("Sort descending"))
+ if not hasattr(self, "popupID"):
+ self.popupId = {'sortAsc': wx.NewId(),
+ 'sortDesc': wx.NewId(),
+ 'calculate': wx.NewId(),
+ 'area': wx.NewId(),
+ 'length': wx.NewId(),
+ 'compact': wx.NewId(),
+ 'fractal': wx.NewId(),
+ 'perimeter': wx.NewId(),
+ 'ncats': wx.NewId(),
+ 'slope': wx.NewId(),
+ 'lsin': wx.NewId(),
+ 'lazimuth': wx.NewId(),
+ 'calculator': wx.NewId(),
+ 'stats': wx.NewId()}
+
+ popupMenu.Append(self.popupId['sortAsc'], text=_("Sort ascending"))
+ popupMenu.Append(self.popupId['sortDesc'], text=_("Sort descending"))
popupMenu.AppendSeparator()
subMenu = wx.Menu()
- popupMenu.AppendMenu(self.popupId['calculate'], _("Calculate (only numeric columns)"),
- subMenu)
- popupMenu.Append(self.popupId['calculator'], text = _("Field calculator"))
+ popupMenu.AppendMenu(self.popupId['calculate'], _(
+ "Calculate (only numeric columns)"), subMenu)
+ popupMenu.Append(
+ self.popupId['calculator'],
+ text=_("Field calculator"))
popupMenu.AppendSeparator()
- popupMenu.Append(self.popupId['stats'], text = _("Statistics"))
-
+ popupMenu.Append(self.popupId['stats'], text=_("Statistics"))
+
if not self.pages['manageTable']:
popupMenu.AppendSeparator()
self.popupId['addCol'] = wx.NewId()
- popupMenu.Append(self.popupId['addCol'], text = _("Add column"))
+ popupMenu.Append(self.popupId['addCol'], text=_("Add column"))
if not self.dbMgrData['editable']:
popupMenu.Enable(self.popupId['addCol'], False)
if not self.dbMgrData['editable']:
popupMenu.Enable(self.popupId['calculator'], False)
-
- if not self.dbMgrData['editable'] or \
- self.columns[self.GetColumn(self._col).GetText()]['ctype'] not in (types.IntType, types.FloatType):
+
+ if not self.dbMgrData['editable'] or self.columns[
+ self.GetColumn(self._col).GetText()]['ctype'] not in (
+ types.IntType, types.FloatType):
popupMenu.Enable(self.popupId['calculate'], False)
-
- subMenu.Append(self.popupId['area'], text = _("Area size"))
- subMenu.Append(self.popupId['length'], text = _("Line length"))
- subMenu.Append(self.popupId['compact'], text = _("Compactness of an area"))
- subMenu.Append(self.popupId['fractal'], text = _("Fractal dimension of boundary defining a polygon"))
- subMenu.Append(self.popupId['perimeter'], text = _("Perimeter length of an area"))
- subMenu.Append(self.popupId['ncats'], text = _("Number of features for each category"))
- subMenu.Append(self.popupId['slope'], text = _("Slope steepness of 3D line"))
- subMenu.Append(self.popupId['lsin'], text = _("Line sinuousity"))
- subMenu.Append(self.popupId['lazimuth'], text = _("Line azimuth"))
-
- self.Bind (wx.EVT_MENU, self.OnColumnSortAsc, id = self.popupId['sortAsc'])
- self.Bind (wx.EVT_MENU, self.OnColumnSortDesc, id = self.popupId['sortDesc'])
- self.Bind(wx.EVT_MENU, self.OnFieldCalculator, id = self.popupId['calculator'])
- self.Bind(wx.EVT_MENU, self.OnFieldStatistics, id = self.popupId['stats'])
+
+ subMenu.Append(self.popupId['area'], text=_("Area size"))
+ subMenu.Append(self.popupId['length'], text=_("Line length"))
+ subMenu.Append(
+ self.popupId['compact'],
+ text=_("Compactness of an area"))
+ subMenu.Append(self.popupId['fractal'], text=_(
+ "Fractal dimension of boundary defining a polygon"))
+ subMenu.Append(
+ self.popupId['perimeter'],
+ text=_("Perimeter length of an area"))
+ subMenu.Append(self.popupId['ncats'], text=_(
+ "Number of features for each category"))
+ subMenu.Append(
+ self.popupId['slope'],
+ text=_("Slope steepness of 3D line"))
+ subMenu.Append(self.popupId['lsin'], text=_("Line sinuousity"))
+ subMenu.Append(self.popupId['lazimuth'], text=_("Line azimuth"))
+
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnColumnSortAsc,
+ id=self.popupId['sortAsc'])
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnColumnSortDesc,
+ id=self.popupId['sortDesc'])
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnFieldCalculator,
+ id=self.popupId['calculator'])
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnFieldStatistics,
+ id=self.popupId['stats'])
if not self.pages['manageTable']:
- self.Bind(wx.EVT_MENU, self.OnAddColumn, id = self.popupId['addCol'])
+ self.Bind(wx.EVT_MENU, self.OnAddColumn, id=self.popupId['addCol'])
- for id in (self.popupId['area'], self.popupId['length'], self.popupId['compact'],
- self.popupId['fractal'], self.popupId['perimeter'], self.popupId['ncats'],
- self.popupId['slope'], self.popupId['lsin'], self.popupId['lazimuth']):
- self.Bind(wx.EVT_MENU, self.OnColumnCompute, id = id)
+ for id in (
+ self.popupId['area'],
+ self.popupId['length'],
+ self.popupId['compact'],
+ self.popupId['fractal'],
+ self.popupId['perimeter'],
+ self.popupId['ncats'],
+ self.popupId['slope'],
+ self.popupId['lsin'],
+ self.popupId['lazimuth']):
+ self.Bind(wx.EVT_MENU, self.OnColumnCompute, id=id)
self.PopupMenu(popupMenu)
popupMenu.Destroy()
@@ -471,25 +515,25 @@
def OnColumnSort(self, event):
"""Column heading left mouse button -> sorting"""
self._col = event.GetColumn()
-
+
self.ColumnSort()
-
+
event.Skip()
def OnColumnSortAsc(self, event):
"""Sort values of selected column (ascending)"""
- self.SortListItems(col = self._col, ascending = True)
+ self.SortListItems(col=self._col, ascending=True)
event.Skip()
def OnColumnSortDesc(self, event):
"""Sort values of selected column (descending)"""
- self.SortListItems(col = self._col, ascending = False)
+ self.SortListItems(col=self._col, ascending=False)
event.Skip()
-
+
def OnColumnCompute(self, event):
"""Compute values of selected column"""
id = event.GetId()
-
+
option = None
if id == self.popupId['area']:
option = 'area'
@@ -509,19 +553,19 @@
option = 'sinuous'
elif id == self.popupId['lazimuth']:
option = 'azimuth'
-
+
if not option:
return
-
+
RunCommand('v.to.db',
- parent = self.parent,
- map = self.mapDBInfo.map,
- layer = self.layer,
- option = option,
- columns = self.GetColumn(self._col).GetText())
-
+ parent=self.parent,
+ map=self.mapDBInfo.map,
+ layer=self.layer,
+ option=option,
+ columns=self.GetColumn(self._col).GetText())
+
self.LoadData(self.layer)
-
+
def ColumnSort(self):
"""Sort values of selected column (self._col)"""
# remove duplicated arrow symbol from column header
@@ -532,14 +576,17 @@
for column in range(self.GetColumnCount()):
info.m_text = self.GetColumn(column).GetText()
self.SetColumn(column, info)
-
+
def OnFieldCalculator(self, event):
"""Calls SQLBuilderUpdate instance"""
if not self.fieldCalc:
- self.fieldCalc = SQLBuilderUpdate(parent = self, id = wx.ID_ANY,
- vectmap = self.dbMgrData['vectName'],
- layer = self.layer,
- column = self.GetColumn(self._col).GetText())
+ self.fieldCalc = SQLBuilderUpdate(
+ parent=self,
+ id=wx.ID_ANY,
+ vectmap=self.dbMgrData['vectName'],
+ layer=self.layer,
+ column=self.GetColumn(
+ self._col).GetText())
self.fieldCalc.Show()
else:
self.fieldCalc.Raise()
@@ -547,31 +594,34 @@
def OnFieldStatistics(self, event):
"""Calls FieldStatistics instance"""
if not self.fieldStats:
- self.fieldStats = FieldStatistics(parent = self, id = wx.ID_ANY)
+ self.fieldStats = FieldStatistics(parent=self, id=wx.ID_ANY)
self.fieldStats.Show()
else:
self.fieldStats.Raise()
selLayer = self.dbMgrData['mapDBInfo'].layers[self.layer]
- self.fieldStats.Update(driver = selLayer['driver'],
- database = selLayer['database'],
- table = selLayer['table'],
- column = self.GetColumn(self._col).GetText())
+ self.fieldStats.Update(driver=selLayer['driver'],
+ database=selLayer['database'],
+ table=selLayer['table'],
+ column=self.GetColumn(self._col).GetText())
def OnAddColumn(self, event):
"""Add column into table"""
table = self.dbMgrData['mapDBInfo'].layers[self.layer]['table']
- dlg = AddColumnDialog(parent = self, title = _('Add column to table <%s>') % table)
+ dlg = AddColumnDialog(
+ parent=self,
+ title=_('Add column to table <%s>') %
+ table)
if not dlg:
return
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetData()
- self.pages['browse'].AddColumn(name = data['name'],
- ctype = data['ctype'],
- length = data['length'])
+ self.pages['browse'].AddColumn(name=data['name'],
+ ctype=data['ctype'],
+ length=data['length'])
dlg.Destroy()
- def SortItems(self, sorter = cmp):
+ def SortItems(self, sorter=cmp):
"""Sort items"""
items = list(self.itemDataMap.keys())
items.sort(self.Sorter)
@@ -579,27 +629,31 @@
# redraw the list
self.Refresh()
-
+
def Sorter(self, key1, key2):
colName = self.GetColumn(self._col).GetText()
ascending = self._colSortFlag[self._col]
try:
- item1 = self.columns[colName]["ctype"](self.itemDataMap[key1][self._col])
- item2 = self.columns[colName]["ctype"](self.itemDataMap[key2][self._col])
+ item1 = self.columns[colName]["ctype"](
+ self.itemDataMap[key1][self._col])
+ item2 = self.columns[colName]["ctype"](
+ self.itemDataMap[key2][self._col])
except ValueError:
item1 = self.itemDataMap[key1][self._col]
item2 = self.itemDataMap[key2][self._col]
- if type(item1) == types.StringType or type(item2) == types.StringTypes:
+ if isinstance(
+ item1, types.StringType) or isinstance(
+ item2, types.StringTypes):
cmpVal = locale.strcoll(str(item1), str(item2))
else:
cmpVal = cmp(item1, item2)
+ # If the items are equal then pick something else to make the sort
+ # value unique
+ if cmpVal == 0:
+ cmpVal = cmp(*self.GetSecondarySortValues(self._col, key1, key2))
- # If the items are equal then pick something else to make the sort value unique
- if cmpVal == 0:
- cmpVal = apply(cmp, self.GetSecondarySortValues(self._col, key1, key2))
-
if ascending:
return cmpVal
else:
@@ -613,22 +667,24 @@
"""Check if list if empty"""
if self.columns:
return False
-
+
return True
+
class DbMgrBase:
- def __init__(self, id = wx.ID_ANY, mapdisplay = None,
- vectorName = None, item = None, giface = None,
- statusbar = None,
+
+ def __init__(self, id=wx.ID_ANY, mapdisplay=None,
+ vectorName=None, item=None, giface=None,
+ statusbar=None,
**kwargs):
- """Base class, which enables usage of separate pages of Attribute Table Manager
+ """Base class, which enables usage of separate pages of Attribute Table Manager
:param id: window id
:param mapdisplay: MapFrame instance
:param vectorName: name of vector map
:param item: item from Layer Tree
:param log: log window
- :param statusbar: widget with statusbar
+ :param statusbar: widget with statusbar
:param kwagrs: other wx.Frame's arguments
"""
@@ -639,7 +695,7 @@
self.mapdisplay = mapdisplay
- if self.mapdisplay:
+ if self.mapdisplay:
self.map = mapdisplay.Map
else:
self.map = None
@@ -647,35 +703,39 @@
if not self.mapdisplay:
pass
elif self.mapdisplay.tree and \
- self.dbMgrData['treeItem'] and not self.dbMgrData['vectName']:
+ self.dbMgrData['treeItem'] and not self.dbMgrData['vectName']:
maptree = self.mapdisplay.tree
- name = maptree.GetLayerInfo(self.dbMgrData['treeItem'], key = 'maplayer').GetName()
+ name = maptree.GetLayerInfo(
+ self.dbMgrData['treeItem'],
+ key='maplayer').GetName()
self.dbMgrData['vectName'] = name
-
+
# vector attributes can be changed only if vector map is in
# the current mapset
mapInfo = None
if self.dbMgrData['vectName']:
- mapInfo = grass.find_file(name = self.dbMgrData['vectName'], element = 'vector')
+ mapInfo = grass.find_file(
+ name=self.dbMgrData['vectName'],
+ element='vector')
if not mapInfo or mapInfo['mapset'] != grass.gisenv()['MAPSET']:
self.dbMgrData['editable'] = False
else:
self.dbMgrData['editable'] = True
-
+
self.giface = giface
# status bar log class
- self.log = Log(statusbar) # -> statusbar
+ self.log = Log(statusbar) # -> statusbar
# -> layers / tables description
self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
- # store information, which pages were initialized
+ # store information, which pages were initialized
self.pages = {
- 'browse' : None,
- 'manageTable' : None,
- 'manageLayer' : None
- }
+ 'browse': None,
+ 'manageTable': None,
+ 'manageLayer': None
+ }
def ChangeVectorMap(self, vectorName):
"""Change of vector map
@@ -683,7 +743,7 @@
Does not import layers of new vector map into pages.
For the import use methods addLayer in DbMgrBrowsePage and DbMgrTablesPage
"""
- if self.pages['browse']:
+ if self.pages['browse']:
self.pages['browse'].DeleteAllPages()
if self.pages['manageTable']:
self.pages['manageTable'].DeleteAllPages()
@@ -695,7 +755,9 @@
# vector attributes can be changed only if vector map is in
# the current mapset
- mapInfo = grass.find_file(name = self.dbMgrData['vectName'], element = 'vector')
+ mapInfo = grass.find_file(
+ name=self.dbMgrData['vectName'],
+ element='vector')
if not mapInfo or mapInfo['mapset'] != grass.gisenv()['MAPSET']:
self.dbMgrData['editable'] = False
else:
@@ -703,9 +765,9 @@
# 'manage layers page
if self.pages['manageLayer']:
- self.pages['manageLayer'].UpdatePage()
+ self.pages['manageLayer'].UpdatePage()
- def CreateDbMgrPage(self, parent, pageName, onlyLayer = -1):
+ def CreateDbMgrPage(self, parent, pageName, onlyLayer=-1):
"""Creates chosen page
:param pageName: can be 'browse' or 'manageTable' or
@@ -714,20 +776,21 @@
:return: created instance of page, if the page has been already
created returns the previously created instance
:return: None if wrong identifier was passed
- """
+ """
if pageName == 'browse':
if not self.pages['browse']:
- self.pages[pageName] = DbMgrBrowsePage(parent = parent, parentDbMgrBase = self,
- onlyLayer = onlyLayer)
+ self.pages[pageName] = DbMgrBrowsePage(
+ parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer)
return self.pages[pageName]
if pageName == 'manageTable':
if not self.pages['manageTable']:
- self.pages[pageName] = DbMgrTablesPage(parent = parent, parentDbMgrBase = self,
- onlyLayer = onlyLayer)
+ self.pages[pageName] = DbMgrTablesPage(
+ parent=parent, parentDbMgrBase=self, onlyLayer=onlyLayer)
return self.pages[pageName]
if pageName == 'manageLayer':
if not self.pages['manageLayer']:
- self.pages[pageName] = DbMgrLayersPage(parent = parent, parentDbMgrBase = self)
+ self.pages[pageName] = DbMgrLayersPage(
+ parent=parent, parentDbMgrBase=self)
return self.pages[pageName]
return None
@@ -740,13 +803,13 @@
# if self.browsePage.GetPageText(page).replace('Layer ', '').strip() == str(layer):
# self.browsePage.DeletePage(page)
# break
- if self.pages['browse']:
+ if self.pages['browse']:
self.pages['browse'].DeletePage(layer)
- if self.pages['manageTable']:
+ if self.pages['manageTable']:
self.pages['manageTable'].DeletePage(layer)
# fetch fresh db info
- self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
+ self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
#
# add new page
@@ -762,7 +825,7 @@
# manage layers page
if self.pages['manageLayer']:
self.pages['manageLayer'].UpdatePage()
-
+
def GetVectorName(self):
"""Get vector name"""
return self.dbMgrData['vectName']
@@ -771,7 +834,9 @@
"""Get layers of vector map which have table"""
return self.dbMgrData['mapDBInfo'].layers.keys()
+
class DbMgrNotebookBase(FN.FlatNotebook):
+
def __init__(self, parent, parentDbMgrBase):
"""Base class for notebook with attribute tables in tabs
@@ -788,18 +853,18 @@
self.map = self.parentDbMgrBase.map
self.mapdisplay = self.parentDbMgrBase.mapdisplay
- #TODO no need to have it in class scope make it local?
- self.listOfCommands = []
+ # TODO no need to have it in class scope make it local?
+ self.listOfCommands = []
self.listOfSQLStatements = []
- #initializet pages
+ # initializet pages
self.pages = self.parentDbMgrBase.pages
# shared data among pages
self.dbMgrData = self.parentDbMgrBase.dbMgrData
# set up virtual lists (each layer)
- ### {layer: list, widgets...}
+ # {layer: list, widgets...}
self.layerPage = {}
# currently selected layer
@@ -809,11 +874,11 @@
self.layers = []
if globalvar.hasAgw:
- dbmStyle = { 'agwStyle' : globalvar.FNPageStyle }
+ dbmStyle = {'agwStyle': globalvar.FNPageStyle}
else:
- dbmStyle = { 'style' : globalvar.FNPageStyle }
+ dbmStyle = {'style': globalvar.FNPageStyle}
- FN.FlatNotebook.__init__(self,parent = self.parent, id = wx.ID_ANY,
+ FN.FlatNotebook.__init__(self, parent=self.parent, id=wx.ID_ANY,
**dbmStyle)
self.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnLayerPageChanged)
@@ -821,25 +886,27 @@
def OnLayerPageChanged(self, event):
"""Layer tab changed"""
- # because of SQL Query notebook
+ # because of SQL Query notebook
if event.GetEventObject() != self:
return
- pageNum = self.GetSelection()
+ pageNum = self.GetSelection()
self.selLayer = self.layers[pageNum]
try:
idCol = self.layerPage[self.selLayer]['whereColumn']
except KeyError:
idCol = None
-
+
try:
# update statusbar
- self.log.write(_("Number of loaded records: %d") % \
- self.FindWindowById(self.layerPage[self.selLayer]['data']).\
- GetItemCount())
+ self.log.write(
+ _("Number of loaded records: %d") %
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['data']). GetItemCount())
except:
pass
-
+
if idCol:
winCol = self.FindWindowById(idCol)
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
@@ -853,15 +920,16 @@
"""
# perform GRASS commands (e.g. v.db.addcolumn)
wx.BeginBusyCursor()
-
+
if len(listOfCommands) > 0:
for cmd in listOfCommands:
- RunCommand(prog = cmd[0],
- quiet = True,
- parent = self,
+ RunCommand(prog=cmd[0],
+ quiet=True,
+ parent=self,
**cmd[1])
-
- self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
+
+ self.dbMgrData['mapDBInfo'] = VectorDBInfo(
+ self.dbMgrData['vectName'])
if self.pages['manageTable']:
self.pages['manageTable'].UpdatePage(self.selLayer)
@@ -869,13 +937,15 @@
self.pages['browse'].UpdatePage(self.selLayer)
# reset list of commands
listOfCommands = []
-
- # perform SQL non-select statements (e.g. 'delete from table where cat=1')
+
+ # perform SQL non-select statements (e.g. 'delete from table where
+ # cat=1')
if len(listOfSQLStatements) > 0:
fd, sqlFilePath = tempfile.mkstemp(text=True)
sqlFile = open(sqlFilePath, 'w')
for sql in listOfSQLStatements:
- enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+ enc = UserSettings.Get(
+ group='atm', key='encoding', subkey='value')
if not enc and 'GRASS_DB_ENCODING' in os.environ:
enc = os.environ['GRASS_DB_ENCODING']
if enc:
@@ -885,25 +955,27 @@
sqlFile.write(os.linesep)
sqlFile.close()
- driver = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["driver"]
- database = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["database"]
-
+ driver = self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]["driver"]
+ database = self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]["database"]
+
Debug.msg(3, 'AttributeManger.ApplyCommands(): %s' %
';'.join(["%s" % s for s in listOfSQLStatements]))
-
+
RunCommand('db.execute',
- parent = self,
- input = sqlFilePath,
- driver = driver,
- database = database)
-
+ parent=self,
+ input=sqlFilePath,
+ driver=driver,
+ database=database)
+
os.close(fd)
os.remove(sqlFilePath)
# reset list of statements
self.listOfSQLStatements = []
-
- wx.EndBusyCursor()
+ wx.EndBusyCursor()
+
def DeletePage(self, layer):
"""Removes layer page"""
if layer not in self.layers:
@@ -931,56 +1003,60 @@
def AddColumn(self, name, ctype, length):
"""Add new column to the table"""
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
-
+
if not name:
- GError(parent = self,
- message = _("Unable to add column to the table. "
- "No column name defined."))
+ GError(parent=self,
+ message=_("Unable to add column to the table. "
+ "No column name defined."))
return False
-
+
# cast type if needed
if ctype == 'double':
ctype = 'double precision'
if ctype != 'varchar':
- length = '' # FIXME
-
+ length = '' # FIXME
+
# check for duplicate items
if name in self.dbMgrData['mapDBInfo'].GetColumns(table):
- GError(parent = self,
- message = _("Column <%(column)s> already exists in table <%(table)s>.") % \
- {'column' : name, 'table' : self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]}
- )
+ GError(
+ parent=self,
+ message=_("Column <%(column)s> already exists in table <%(table)s>.") % {
+ 'column': name,
+ 'table': self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]["table"]})
return False
# add v.db.addcolumn command to the list
if ctype == 'varchar':
ctype += ' (%d)' % length
self.listOfCommands.append(('v.db.addcolumn',
- { 'map' : self.dbMgrData['vectName'],
- 'layer' : self.selLayer,
- 'columns' : '%s %s' % (name, ctype) }
+ {'map': self.dbMgrData['vectName'],
+ 'layer': self.selLayer,
+ 'columns': '%s %s' % (name, ctype)}
))
# apply changes
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
+
return True
def GetAddedLayers(self):
"""Get list of added layers"""
return self.layers[:]
+
class DbMgrBrowsePage(DbMgrNotebookBase):
- def __init__(self, parent, parentDbMgrBase, onlyLayer = -1):
+
+ def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
"""Browse page class
:param parent: GUI parent
:param parentDbMgrBase: instance of DbMgrBase class
:param onlyLayer: create only tab of given layer, if -1 creates
- tabs of all layers
+ tabs of all layers
"""
- DbMgrNotebookBase.__init__(self, parent = parent,
- parentDbMgrBase = parentDbMgrBase)
+ DbMgrNotebookBase.__init__(self, parent=parent,
+ parentDbMgrBase=parentDbMgrBase)
# for Sql Query notebook adaptation on current width
self.sqlBestSize = None
@@ -991,10 +1067,13 @@
self.AddLayer(layer)
if self.layers:
- self.SetSelection(0)
+ self.SetSelection(0)
self.selLayer = self.layers[0]
- self.log.write(_("Number of loaded records: %d") % \
- self.FindWindowById(self.layerPage[self.selLayer]['data']).GetItemCount())
+ self.log.write(
+ _("Number of loaded records: %d") %
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['data']).GetItemCount())
# query map layer (if parent (GMFrame) is given)
self.qlayer = None
@@ -1002,30 +1081,31 @@
# sqlbuilder
self.builder = None
- def AddLayer(self, layer, pos = -1):
+ def AddLayer(self, layer, pos=-1):
"""Adds tab which represents table and enables browse it
:param layer: vector map layer conntected to table
:param pos: position of tab, if -1 it is added to end
- :return: True if layer was added
+ :return: True if layer was added
:return: False if layer was not added - layer has been already
- added or has empty table or does not exist
+ added or has empty table or does not exist
"""
if layer in self.layers or \
- layer not in self.parentDbMgrBase.GetVectorLayers():
- return False
+ layer not in self.parentDbMgrBase.GetVectorLayers():
+ return False
- panel = wx.Panel(parent = self, id = wx.ID_ANY)
-
- #IMPORTANT NOTE: wx.StaticBox MUST be defined BEFORE any of the
+ panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+ # IMPORTANT NOTE: wx.StaticBox MUST be defined BEFORE any of the
# controls that are placed IN the wx.StaticBox, or it will freeze
# on the Mac
-
- listBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
- label = " %s " % _("Attribute data - right-click to edit/manage records"))
+
+ listBox = wx.StaticBox(
+ parent=panel, id=wx.ID_ANY, label=" %s " %
+ _("Attribute data - right-click to edit/manage records"))
listSizer = wx.StaticBoxSizer(listBox, wx.VERTICAL)
-
+
win = VirtualAttributeList(panel, self.log,
self.dbMgrData, layer, self.pages)
if win.IsEmpty():
@@ -1033,165 +1113,195 @@
return False
self.layers.append(layer)
-
+
win.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnDataItemActivated)
self.layerPage[layer] = {'browsePage': panel.GetId()}
-
+
label = _("Table")
if not self.dbMgrData['editable']:
label += _(" (readonly)")
if pos == -1:
- pos = self.GetPageCount()
- self.InsertPage(pos, page = panel,
- text = " %d / %s %s" % \
- (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
-
+ pos = self.GetPageCount()
+ self.InsertPage(
+ pos, page=panel, text=" %d / %s %s" %
+ (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+
pageSizer = wx.BoxSizer(wx.VERTICAL)
- sqlQueryPanel = wx.Panel(parent = panel, id = wx.ID_ANY)
+ sqlQueryPanel = wx.Panel(parent=panel, id=wx.ID_ANY)
- # attribute data
- sqlBox = wx.StaticBox(parent = sqlQueryPanel, id = wx.ID_ANY,
- label = " %s " % _("SQL Query"))
+ # attribute data
+ sqlBox = wx.StaticBox(parent=sqlQueryPanel, id=wx.ID_ANY,
+ label=" %s " % _("SQL Query"))
sqlSizer = wx.StaticBoxSizer(sqlBox, wx.VERTICAL)
- win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp) #wxMSW
- win.Bind(wx.EVT_RIGHT_UP, self.OnDataRightUp) #wxGTK
- if UserSettings.Get(group = 'atm', key = 'leftDbClick', subkey = 'selection') == 0:
+ win.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnDataRightUp) # wxMSW
+ win.Bind(wx.EVT_RIGHT_UP, self.OnDataRightUp) # wxGTK
+ if UserSettings.Get(group='atm', key='leftDbClick',
+ subkey='selection') == 0:
win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataItemEdit)
win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataItemEdit)
else:
win.Bind(wx.EVT_LEFT_DCLICK, self.OnDataDrawSelected)
win.Bind(wx.EVT_COMMAND_LEFT_DCLICK, self.OnDataDrawSelected)
-
- listSizer.Add(item = win, proportion = 1,
- flag = wx.EXPAND | wx.ALL,
- border = 3)
+ listSizer.Add(item=win, proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
+
# sql statement box
FNPageStyle = FN.FNB_NO_NAV_BUTTONS | \
- FN.FNB_NO_X_BUTTON
+ FN.FNB_NO_X_BUTTON
if globalvar.hasAgw:
- dbmStyle = { 'agwStyle' : FNPageStyle }
+ dbmStyle = {'agwStyle': FNPageStyle}
else:
- dbmStyle = { 'style' : FNPageStyle }
- sqlNtb = FN.FlatNotebook(parent = sqlQueryPanel, id = wx.ID_ANY,
+ dbmStyle = {'style': FNPageStyle}
+ sqlNtb = FN.FlatNotebook(parent=sqlQueryPanel, id=wx.ID_ANY,
**dbmStyle)
# Simple tab
- simpleSqlPanel = wx.Panel(parent = sqlNtb, id = wx.ID_ANY)
- sqlNtb.AddPage(page = simpleSqlPanel,
- text = _('Simple'))
+ simpleSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
+ sqlNtb.AddPage(page=simpleSqlPanel,
+ text=_('Simple'))
- btnApply = wx.Button(parent = simpleSqlPanel, id = wx.ID_APPLY, name = 'btnApply')
- btnApply.SetToolTipString(_("Apply SELECT statement and reload data records"))
+ btnApply = wx.Button(
+ parent=simpleSqlPanel,
+ id=wx.ID_APPLY,
+ name='btnApply')
+ btnApply.SetToolTipString(
+ _("Apply SELECT statement and reload data records"))
btnApply.Bind(wx.EVT_BUTTON, self.OnApplySqlStatement)
- whereSimpleSqlPanel = wx.Panel(parent = simpleSqlPanel, id = wx.ID_ANY, name = 'wherePanel')
- sqlWhereColumn = wx.ComboBox(parent = whereSimpleSqlPanel, id = wx.ID_ANY,
- size = (150,-1),
- style = wx.CB_SIMPLE | wx.CB_READONLY,
- choices = self.dbMgrData['mapDBInfo'].GetColumns(self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+ whereSimpleSqlPanel = wx.Panel(
+ parent=simpleSqlPanel,
+ id=wx.ID_ANY,
+ name='wherePanel')
+ sqlWhereColumn = wx.ComboBox(
+ parent=whereSimpleSqlPanel, id=wx.ID_ANY, size=(150, -1),
+ style=wx.CB_SIMPLE | wx.CB_READONLY,
+ choices=self.dbMgrData['mapDBInfo'].GetColumns(
+ self.dbMgrData['mapDBInfo'].layers[layer]['table']))
sqlWhereColumn.SetSelection(0)
- sqlWhereCond = wx.Choice(parent = whereSimpleSqlPanel, id = wx.ID_ANY,
- size = (55,-1),
- choices = ['=', '!=', '<', '<=', '>', '>='])
+ sqlWhereCond = wx.Choice(parent=whereSimpleSqlPanel, id=wx.ID_ANY,
+ size=(55, -1),
+ choices=['=', '!=', '<', '<=', '>', '>='])
sqlWhereCond.SetSelection(0)
- sqlWhereValue = wx.TextCtrl(parent = whereSimpleSqlPanel, id = wx.ID_ANY, value = "",
- style = wx.TE_PROCESS_ENTER)
- sqlWhereValue.SetToolTipString(_("Example: %s") % "MULTILANE = 'no' AND OBJECTID < 10")
+ sqlWhereValue = wx.TextCtrl(
+ parent=whereSimpleSqlPanel,
+ id=wx.ID_ANY,
+ value="",
+ style=wx.TE_PROCESS_ENTER)
+ sqlWhereValue.SetToolTipString(
+ _("Example: %s") %
+ "MULTILANE = 'no' AND OBJECTID < 10")
- sqlLabel = wx.StaticText(parent = simpleSqlPanel, id = wx.ID_ANY,
- label = "SELECT * FROM %s WHERE " % \
- self.dbMgrData['mapDBInfo'].layers[layer]['table'])
+ sqlLabel = wx.StaticText(
+ parent=simpleSqlPanel,
+ id=wx.ID_ANY,
+ label="SELECT * FROM %s WHERE " %
+ self.dbMgrData['mapDBInfo'].layers[layer]['table'])
# Advanced tab
- advancedSqlPanel = wx.Panel(parent = sqlNtb, id = wx.ID_ANY)
- sqlNtb.AddPage(page = advancedSqlPanel,
- text = _('Builder'))
+ advancedSqlPanel = wx.Panel(parent=sqlNtb, id=wx.ID_ANY)
+ sqlNtb.AddPage(page=advancedSqlPanel,
+ text=_('Builder'))
- btnSqlBuilder = wx.Button(parent = advancedSqlPanel, id = wx.ID_ANY, label = _("SQL Builder"))
+ btnSqlBuilder = wx.Button(
+ parent=advancedSqlPanel,
+ id=wx.ID_ANY,
+ label=_("SQL Builder"))
btnSqlBuilder.Bind(wx.EVT_BUTTON, self.OnBuilder)
- sqlStatement = wx.TextCtrl(parent = advancedSqlPanel, id = wx.ID_ANY,
- value = "SELECT * FROM %s" % \
- self.dbMgrData['mapDBInfo'].layers[layer]['table'],
- style = wx.TE_PROCESS_ENTER)
- sqlStatement.SetToolTipString(_("Example: %s") % "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' AND OBJECTID < 10")
+ sqlStatement = wx.TextCtrl(
+ parent=advancedSqlPanel,
+ id=wx.ID_ANY,
+ value="SELECT * FROM %s" %
+ self.dbMgrData['mapDBInfo'].layers[layer]['table'],
+ style=wx.TE_PROCESS_ENTER)
+ sqlStatement.SetToolTipString(
+ _("Example: %s") %
+ "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' AND OBJECTID < 10")
sqlWhereValue.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
sqlStatement.Bind(wx.EVT_TEXT_ENTER, self.OnApplySqlStatement)
# Simple tab layout
- simpleSqlSizer = wx.GridBagSizer (hgap = 5, vgap = 5)
+ simpleSqlSizer = wx.GridBagSizer(hgap=5, vgap=5)
- sqlSimpleWhereSizer= wx.BoxSizer(wx.HORIZONTAL)
+ sqlSimpleWhereSizer = wx.BoxSizer(wx.HORIZONTAL)
- sqlSimpleWhereSizer.Add(item = sqlWhereColumn,
- flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL| wx.LEFT,
- border = 3)
- sqlSimpleWhereSizer.Add(item = sqlWhereCond,
- flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
- border = 3)
- sqlSimpleWhereSizer.Add(item = sqlWhereValue, proportion = 1,
- flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
- border = 3)
+ sqlSimpleWhereSizer.Add(
+ item=sqlWhereColumn,
+ flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+ border=3)
+ sqlSimpleWhereSizer.Add(
+ item=sqlWhereCond,
+ flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+ border=3)
+ sqlSimpleWhereSizer.Add(
+ item=sqlWhereValue,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL | wx.LEFT,
+ border=3)
whereSimpleSqlPanel.SetSizer(sqlSimpleWhereSizer)
- simpleSqlSizer.Add(item = sqlLabel, border = 5, pos = (0, 0),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT)
- simpleSqlSizer.Add(item = whereSimpleSqlPanel, border = 5, pos = (0, 1),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.EXPAND)
- simpleSqlSizer.Add(item = btnApply, border = 5, pos = (0, 2),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.TOP)
+ simpleSqlSizer.Add(item=sqlLabel, border=5, pos=(0, 0),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT)
+ simpleSqlSizer.Add(item=whereSimpleSqlPanel, border=5, pos=(0, 1),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.EXPAND)
+ simpleSqlSizer.Add(item=btnApply, border=5, pos=(0, 2),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP)
simpleSqlSizer.AddGrowableCol(1)
simpleSqlPanel.SetSizer(simpleSqlSizer)
# Advanced tab layout
- advancedSqlSizer = wx.FlexGridSizer (cols = 2, hgap = 5, vgap = 5)
+ advancedSqlSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
advancedSqlSizer.AddGrowableCol(0)
- advancedSqlSizer.Add(item = sqlStatement,
- flag = wx.EXPAND | wx.ALL, border = 5)
- advancedSqlSizer.Add(item = btnSqlBuilder,
- flag = wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT | wx.BOTTOM, border = 5)
+ advancedSqlSizer.Add(item=sqlStatement,
+ flag=wx.EXPAND | wx.ALL, border=5)
+ advancedSqlSizer.Add(
+ item=btnSqlBuilder,
+ flag=wx.ALIGN_RIGHT | wx.TOP | wx.RIGHT | wx.BOTTOM,
+ border=5)
- sqlSizer.Add(item = sqlNtb,
- flag = wx.ALL | wx.EXPAND,
- border = 3)
+ sqlSizer.Add(item=sqlNtb,
+ flag=wx.ALL | wx.EXPAND,
+ border=3)
advancedSqlPanel.SetSizer(advancedSqlSizer)
- pageSizer.Add(item = listSizer,
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
+ pageSizer.Add(item=listSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
sqlQueryPanel.SetSizer(sqlSizer)
-
- pageSizer.Add(item = sqlQueryPanel,
- proportion = 0,
- flag = wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
- border = 5)
+ pageSizer.Add(item=sqlQueryPanel,
+ proportion=0,
+ flag=wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.EXPAND,
+ border=5)
+
panel.SetSizer(pageSizer)
-
+
sqlNtb.Bind(wx.EVT_SIZE, self.OnSqlQuerySizeWrap(layer))
- self.layerPage[layer]['data'] = win.GetId()
- self.layerPage[layer]['sqlNtb'] = sqlNtb.GetId()
+ self.layerPage[layer]['data'] = win.GetId()
+ self.layerPage[layer]['sqlNtb'] = sqlNtb.GetId()
self.layerPage[layer]['whereColumn'] = sqlWhereColumn.GetId()
self.layerPage[layer]['whereOperator'] = sqlWhereCond.GetId()
- self.layerPage[layer]['where'] = sqlWhereValue.GetId()
- self.layerPage[layer]['builder'] = btnSqlBuilder.GetId()
+ self.layerPage[layer]['where'] = sqlWhereValue.GetId()
+ self.layerPage[layer]['builder'] = btnSqlBuilder.GetId()
self.layerPage[layer]['statement'] = sqlStatement.GetId()
- self.layerPage[layer]['sqlIsReduced'] = False # for SQL Query adaptation on width
+ # for SQL Query adaptation on width
+ self.layerPage[layer]['sqlIsReduced'] = False
return True
def OnSqlQuerySizeWrap(self, layer):
"""Helper function"""
- return lambda event : self.OnSqlQuerySize(event, layer)
+ return lambda event: self.OnSqlQuerySize(event, layer)
def OnSqlQuerySize(self, event, layer):
"""Adapts SQL Query Simple tab on current width"""
@@ -1200,8 +1310,8 @@
if not self.sqlBestSize:
self.sqlBestSize = sqlNtb.GetBestSize()
- size = sqlNtb.GetSize()
- sqlReduce = self.sqlBestSize[0] > size[0]
+ size = sqlNtb.GetSize()
+ sqlReduce = self.sqlBestSize[0] > size[0]
if (sqlReduce and self.layerPage[layer]['sqlIsReduced']) or \
(not sqlReduce and not self.layerPage[layer]['sqlIsReduced']):
event.Skip()
@@ -1247,24 +1357,40 @@
self.popupDataID10 = wx.NewId()
self.popupDataID11 = wx.NewId()
- self.Bind(wx.EVT_MENU, self.OnDataItemEdit, id = self.popupDataID1)
- self.Bind(wx.EVT_MENU, self.OnDataItemAdd, id = self.popupDataID2)
- self.Bind(wx.EVT_MENU, self.OnDataItemDelete, id = self.popupDataID3)
- self.Bind(wx.EVT_MENU, self.OnDataItemDeleteAll, id = self.popupDataID4)
- self.Bind(wx.EVT_MENU, self.OnDataSelectAll, id = self.popupDataID5)
- self.Bind(wx.EVT_MENU, self.OnDataSelectNone, id = self.popupDataID6)
- self.Bind(wx.EVT_MENU, self.OnDataDrawSelected, id = self.popupDataID7)
- self.Bind(wx.EVT_MENU, self.OnDataDrawSelectedZoom, id = self.popupDataID8)
- self.Bind(wx.EVT_MENU, self.OnExtractSelected, id = self.popupDataID9)
- self.Bind(wx.EVT_MENU, self.OnDeleteSelected, id = self.popupDataID11)
- self.Bind(wx.EVT_MENU, self.OnDataReload, id = self.popupDataID10)
+ self.Bind(wx.EVT_MENU, self.OnDataItemEdit, id=self.popupDataID1)
+ self.Bind(wx.EVT_MENU, self.OnDataItemAdd, id=self.popupDataID2)
+ self.Bind(wx.EVT_MENU, self.OnDataItemDelete, id=self.popupDataID3)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnDataItemDeleteAll,
+ id=self.popupDataID4)
+ self.Bind(wx.EVT_MENU, self.OnDataSelectAll, id=self.popupDataID5)
+ self.Bind(wx.EVT_MENU, self.OnDataSelectNone, id=self.popupDataID6)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnDataDrawSelected,
+ id=self.popupDataID7)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnDataDrawSelectedZoom,
+ id=self.popupDataID8)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnExtractSelected,
+ id=self.popupDataID9)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnDeleteSelected,
+ id=self.popupDataID11)
+ self.Bind(wx.EVT_MENU, self.OnDataReload, id=self.popupDataID10)
tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
# generate popup-menu
menu = wx.Menu()
menu.Append(self.popupDataID1, _("Edit selected record"))
selected = tlist.GetFirstSelected()
- if not self.dbMgrData['editable'] or selected == -1 or tlist.GetNextSelected(selected) != -1:
+ if not self.dbMgrData[
+ 'editable'] or selected == -1 or tlist.GetNextSelected(selected) != -1:
menu.Enable(self.popupDataID1, False)
menu.Append(self.popupDataID2, _("Insert new record"))
menu.Append(self.popupDataID3, _("Delete selected record(s)"))
@@ -1278,7 +1404,9 @@
menu.Append(self.popupDataID6, _("Deselect all"))
menu.AppendSeparator()
menu.Append(self.popupDataID7, _("Highlight selected features"))
- menu.Append(self.popupDataID8, _("Highlight selected features and zoom"))
+ menu.Append(
+ self.popupDataID8,
+ _("Highlight selected features and zoom"))
if not self.map or len(tlist.GetSelectedItems()) == 0:
menu.Enable(self.popupDataID7, False)
menu.Enable(self.popupDataID8, False)
@@ -1297,66 +1425,68 @@
menu.Destroy()
# update statusbar
- self.log.write(_("Number of loaded records: %d") % \
- tlist.GetItemCount())
+ self.log.write(_("Number of loaded records: %d") %
+ tlist.GetItemCount())
def OnDataItemEdit(self, event):
"""Edit selected record of the attribute table"""
- tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
- item = tlist.GetFirstSelected()
+ tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
+ item = tlist.GetFirstSelected()
if item == -1:
return
- table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+ table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
- cat = tlist.itemCatsMap[tlist.itemIndexMap[item]]
+ cat = tlist.itemCatsMap[tlist.itemIndexMap[item]]
# (column name, value)
data = []
# collect names of all visible columns
columnName = []
- for i in range(tlist.GetColumnCount()):
+ for i in range(tlist.GetColumnCount()):
columnName.append(tlist.GetColumn(i).GetText())
-
# key column must be always presented
if keyColumn not in columnName:
- columnName.insert(0, keyColumn) # insert key column on first position
+ # insert key column on first position
+ columnName.insert(0, keyColumn)
data.append((keyColumn, str(cat)))
keyId = 0
missingKey = True
else:
missingKey = False
-
+
# add other visible columns
for i in range(len(columnName)):
- ctype = self.dbMgrData['mapDBInfo'].tables[table][columnName[i]]['ctype']
- ctypeStr = self.dbMgrData['mapDBInfo'].tables[table][columnName[i]]['type']
- if columnName[i] == keyColumn: # key
- if missingKey is False:
+ ctype = self.dbMgrData['mapDBInfo'].tables[
+ table][columnName[i]]['ctype']
+ ctypeStr = self.dbMgrData['mapDBInfo'].tables[
+ table][columnName[i]]['type']
+ if columnName[i] == keyColumn: # key
+ if missingKey is False:
data.append((columnName[i], ctype, ctypeStr, str(cat)))
keyId = i
else:
if missingKey is True:
- value = tlist.GetItem(item, i-1).GetText()
+ value = tlist.GetItem(item, i - 1).GetText()
else:
value = tlist.GetItem(item, i).GetText()
data.append((columnName[i], ctype, ctypeStr, value))
- dlg = ModifyTableRecord(parent = self,
- title = _("Update existing record"),
- data = data, keyEditable = (keyId, False))
+ dlg = ModifyTableRecord(parent=self,
+ title=_("Update existing record"),
+ data=data, keyEditable=(keyId, False))
if dlg.ShowModal() == wx.ID_OK:
- values = dlg.GetValues() # string
+ values = dlg.GetValues() # string
updateList = list()
try:
- for i in range(len(values)):
- if i == keyId: # skip key column
+ for i in range(len(values)):
+ if i == keyId: # skip key column
continue
if tlist.GetItem(item, i).GetText() == values[i]:
- continue # no change
-
+ continue # no change
+
column = tlist.columns[columnName[i]]
if len(values[i]) > 0:
try:
@@ -1364,89 +1494,99 @@
idx = i - 1
else:
idx = i
-
+
if column['ctype'] != types.StringType:
- tlist.itemDataMap[item][idx] = column['ctype'] (values[i])
- else: # -> string
+ tlist.itemDataMap[item][
+ idx] = column['ctype'](values[i])
+ else: # -> string
tlist.itemDataMap[item][idx] = values[i]
except ValueError:
- raise ValueError(_("Value '%(value)s' needs to be entered as %(type)s.") % \
- {'value' : str(values[i]),
- 'type' : column['type']})
-
+ raise ValueError(_("Value '%(value)s' needs to be entered as %(type)s.") %
+ {'value': str(values[i]),
+ 'type': column['type']})
+
if column['ctype'] == types.StringType:
- if "'" in values[i]: # replace "'" -> "''"
+ if "'" in values[i]: # replace "'" -> "''"
values[i] = values[i].replace("'", "''")
- updateList.append("%s='%s'" % (columnName[i], values[i]))
+ updateList.append(
+ "%s='%s'" %
+ (columnName[i], values[i]))
else:
- updateList.append("%s=%s" % (columnName[i], values[i]))
- else: # -> NULL
+ updateList.append(
+ "%s=%s" %
+ (columnName[i], values[i]))
+ else: # -> NULL
updateList.append("%s=NULL" % (columnName[i]))
except ValueError as err:
- GError(parent = self,
- message = _("Unable to update existing record.\n%s") % err,
- showTraceback = False)
+ GError(
+ parent=self,
+ message=_("Unable to update existing record.\n%s") %
+ err,
+ showTraceback=False)
self.OnDataItemEdit(event)
return
-
+
if updateList:
- self.listOfSQLStatements.append('UPDATE %s SET %s WHERE %s=%d' % \
- (table, ','.join(updateList),
- keyColumn, cat))
- self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
+ self.listOfSQLStatements.append(
+ 'UPDATE %s SET %s WHERE %s=%d' %
+ (table, ','.join(updateList), keyColumn, cat))
+ self.ApplyCommands(
+ self.listOfCommands,
+ self.listOfSQLStatements)
+
tlist.Update()
-
+
def OnDataItemAdd(self, event):
"""Add new record to the attribute table"""
- tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
- table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+ tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
+ table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
-
+
# (column name, value)
data = []
# collect names of all visible columns
columnName = []
- for i in range(tlist.GetColumnCount()):
+ for i in range(tlist.GetColumnCount()):
columnName.append(tlist.GetColumn(i).GetText())
# maximal category number
if len(tlist.itemCatsMap.values()) > 0:
maxCat = max(tlist.itemCatsMap.values())
else:
- maxCat = 0 # starting category '1'
-
+ maxCat = 0 # starting category '1'
+
# key column must be always presented
if keyColumn not in columnName:
- columnName.insert(0, keyColumn) # insert key column on first position
+ # insert key column on first position
+ columnName.insert(0, keyColumn)
data.append((keyColumn, str(maxCat + 1)))
missingKey = True
else:
missingKey = False
-
+
# add other visible columns
colIdx = 0
keyId = -1
for col in columnName:
ctype = self.dbMgrData['mapDBInfo'].tables[table][col]['ctype']
ctypeStr = self.dbMgrData['mapDBInfo'].tables[table][col]['type']
- if col == keyColumn: # key
- if missingKey is False:
+ if col == keyColumn: # key
+ if missingKey is False:
data.append((col, ctype, ctypeStr, str(maxCat + 1)))
keyId = colIdx
else:
data.append((col, ctype, ctypeStr, ''))
-
+
colIdx += 1
-
- dlg = ModifyTableRecord(parent = self,
- title = _("Insert new record"),
- data = data, keyEditable = (keyId, True))
+ dlg = ModifyTableRecord(parent=self,
+ title=_("Insert new record"),
+ data=data, keyEditable=(keyId, True))
+
if dlg.ShowModal() == wx.ID_OK:
- try: # get category number
- cat = int(dlg.GetValues(columns = [keyColumn])[0])
+ try: # get category number
+ cat = int(dlg.GetValues(columns=[keyColumn])[0])
except:
cat = -1
@@ -1455,21 +1595,21 @@
raise ValueError(_("Record with category number %d "
"already exists in the table.") % cat)
- values = dlg.GetValues() # values (need to be casted)
+ values = dlg.GetValues() # values (need to be casted)
columnsString = ''
- valuesString = ''
-
+ valuesString = ''
+
for i in range(len(values)):
- if len(values[i]) == 0: # NULL
+ if len(values[i]) == 0: # NULL
if columnName[i] == keyColumn:
raise ValueError(_("Category number (column %s)"
" is missing.") % keyColumn)
else:
continue
-
+
try:
if tlist.columns[columnName[i]]['ctype'] == int:
- # values[i] is stored as text.
+ # values[i] is stored as text.
values[i] = int(float(values[i]))
elif tlist.columns[columnName[i]]['ctype'] == float:
values[i] = float(values[i])
@@ -1478,74 +1618,76 @@
{'value': values[i],
'type': tlist.columns[columnName[i]]['type']})
columnsString += '%s,' % columnName[i]
-
+
if tlist.columns[columnName[i]]['ctype'] == str:
valuesString += "'%s'," % values[i]
else:
valuesString += "%s," % values[i]
-
+
except ValueError as err:
- GError(parent = self,
- message = _("Unable to insert new record.\n%s") % err,
- showTraceback = False)
+ GError(parent=self,
+ message=_("Unable to insert new record.\n%s") % err,
+ showTraceback=False)
self.OnDataItemAdd(event)
return
-
- # remove category if need
+
+ # remove category if need
if missingKey is True:
del values[0]
-
+
# add new item to the tlist
if len(tlist.itemIndexMap) > 0:
index = max(tlist.itemIndexMap) + 1
else:
index = 0
-
+
tlist.itemIndexMap.append(index)
tlist.itemDataMap[index] = values
tlist.itemCatsMap[index] = cat
tlist.SetItemCount(tlist.GetItemCount() + 1)
- self.listOfSQLStatements.append('INSERT INTO %s (%s) VALUES(%s)' % \
- (table,
- columnsString.rstrip(','),
- valuesString.rstrip(',')))
-
+ self.listOfSQLStatements.append('INSERT INTO %s (%s) VALUES(%s)' %
+ (table,
+ columnsString.rstrip(','),
+ valuesString.rstrip(',')))
+
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
def OnDataItemDelete(self, event):
"""Delete selected item(s) from the tlist (layer/category pair)"""
dlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
item = dlist.GetFirstSelected()
-
- table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
- key = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["key"]
-
+
+ table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
+ key = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["key"]
+
indices = []
# collect SQL statements
while item != -1:
index = dlist.itemIndexMap[item]
indices.append(index)
-
+
cat = dlist.itemCatsMap[index]
-
- self.listOfSQLStatements.append('DELETE FROM %s WHERE %s=%d' % \
- (table, key, cat))
-
+
+ self.listOfSQLStatements.append('DELETE FROM %s WHERE %s=%d' %
+ (table, key, cat))
+
item = dlist.GetNextSelected(item)
-
- if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
- deleteDialog = wx.MessageBox(parent = self,
- message = _("Selected data records (%d) will be permanently deleted "
- "from table. Do you want to delete them?") % \
- (len(self.listOfSQLStatements)),
- caption = _("Delete records"),
- style = wx.YES_NO | wx.CENTRE)
+
+ if UserSettings.Get(
+ group='atm', key='askOnDeleteRec', subkey='enabled'):
+ deleteDialog = wx.MessageBox(
+ parent=self,
+ message=_(
+ "Selected data records (%d) will be permanently deleted "
+ "from table. Do you want to delete them?") %
+ (len(self.listOfSQLStatements)),
+ caption=_("Delete records"),
+ style=wx.YES_NO | wx.CENTRE)
if deleteDialog != wx.YES:
self.listOfSQLStatements = []
return False
-
+
# restore maps
i = 0
indexTemp = copy.copy(dlist.itemIndexMap)
@@ -1554,7 +1696,7 @@
dlist.itemDataMap = {}
catsTemp = copy.deepcopy(dlist.itemCatsMap)
dlist.itemCatsMap = {}
-
+
i = 0
for index in indexTemp:
if index in indices:
@@ -1562,37 +1704,41 @@
dlist.itemIndexMap.append(i)
dlist.itemDataMap[i] = dataTemp[index]
dlist.itemCatsMap[i] = catsTemp[index]
-
+
i += 1
-
+
dlist.SetItemCount(len(dlist.itemIndexMap))
-
+
# deselect items
item = dlist.GetFirstSelected()
while item != -1:
- dlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+ dlist.SetItemState(
+ item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
item = dlist.GetNextSelected(item)
-
+
# submit SQL statements
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
+
return True
def OnDataItemDeleteAll(self, event):
"""Delete all items from the list"""
dlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
- if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
- deleteDialog = wx.MessageBox(parent = self,
- message = _("All data records (%d) will be permanently deleted "
- "from table. Do you want to delete them?") % \
- (len(dlist.itemIndexMap)),
- caption = _("Delete records"),
- style = wx.YES_NO | wx.CENTRE)
+ if UserSettings.Get(
+ group='atm', key='askOnDeleteRec', subkey='enabled'):
+ deleteDialog = wx.MessageBox(
+ parent=self,
+ message=_(
+ "All data records (%d) will be permanently deleted "
+ "from table. Do you want to delete them?") %
+ (len(dlist.itemIndexMap)),
+ caption=_("Delete records"),
+ style=wx.YES_NO | wx.CENTRE)
if deleteDialog != wx.YES:
return
dlist.DeleteAllItems()
- dlist.itemDataMap = {}
+ dlist.itemDataMap = {}
dlist.itemIndexMap = []
dlist.SetItemCount(0)
@@ -1600,45 +1746,48 @@
self.listOfSQLStatements.append('DELETE FROM %s' % table)
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
+
event.Skip()
def _drawSelected(self, zoom, selectedOnly=True):
"""Highlight selected features"""
if not self.map or not self.mapdisplay:
return
-
+
tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
if selectedOnly:
fn = tlist.GetSelectedItems
else:
fn = tlist.GetItems
-
+
cats = map(int, fn())
-
+
digitToolbar = None
if 'vdigit' in self.mapdisplay.toolbars:
digitToolbar = self.mapdisplay.toolbars['vdigit']
- if digitToolbar and digitToolbar.GetLayer() and \
- digitToolbar.GetLayer().GetName() == self.dbMgrData['vectName']:
+ if digitToolbar and digitToolbar.GetLayer() and digitToolbar.GetLayer(
+ ).GetName() == self.dbMgrData['vectName']:
display = self.mapdisplay.GetMapWindow().GetDisplay()
- display.SetSelected(cats, layer = self.selLayer)
+ display.SetSelected(cats, layer=self.selLayer)
if zoom:
n, s, w, e = display.GetRegionSelected()
- self.mapdisplay.Map.GetRegion(n = n, s = s, w = w, e = e,
- update = True)
+ self.mapdisplay.Map.GetRegion(n=n, s=s, w=w, e=e,
+ update=True)
else:
# add map layer with higlighted vector features
- self.AddQueryMapLayer(selectedOnly) # -> self.qlayer
+ self.AddQueryMapLayer(selectedOnly) # -> self.qlayer
# set opacity based on queried layer
if self.parent and self.mapdisplay.tree and \
self.dbMgrData['treeItem']:
- maptree = self.mapdisplay.tree # TODO: giface
- opacity = maptree.GetLayerInfo(self.dbMgrData['treeItem'], key = 'maplayer').GetOpacity()
+ maptree = self.mapdisplay.tree # TODO: giface
+ opacity = maptree.GetLayerInfo(
+ self.dbMgrData['treeItem'],
+ key='maplayer').GetOpacity()
self.qlayer.SetOpacity(opacity)
if zoom:
- keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
+ keyColumn = self.dbMgrData[
+ 'mapDBInfo'].layers[self.selLayer]['key']
where = ''
for range in ListOfCatsToRange(cats).split(','):
if '-' in range:
@@ -1649,16 +1798,16 @@
else:
where += '%s = %d or ' % (keyColumn, int(range))
where = where.rstrip('or ')
-
+
select = RunCommand('v.db.select',
- parent = self,
- read = True,
- quiet = True,
- flags = 'r',
- map = self.dbMgrData['mapDBInfo'].map,
- layer = int(self.selLayer),
- where = where)
-
+ parent=self,
+ read=True,
+ quiet=True,
+ flags='r',
+ map=self.dbMgrData['mapDBInfo'].map,
+ layer=int(self.selLayer),
+ where=where)
+
region = {}
for line in select.splitlines():
key, value = line.split('=')
@@ -1666,25 +1815,27 @@
nsdist = ewdist = 0
renderer = self.mapdisplay.GetMap()
- nsdist = 10 * ((renderer.GetCurrentRegion()['n'] - renderer.GetCurrentRegion()['s']) /
- renderer.height)
- ewdist = 10 * ((renderer.GetCurrentRegion()['e'] - renderer.GetCurrentRegion()['w']) /
- renderer.width)
+ nsdist = 10 * ((renderer.GetCurrentRegion()
+ ['n'] - renderer.GetCurrentRegion()['s']) / renderer.height)
+ ewdist = 10 * ((renderer.GetCurrentRegion()
+ ['e'] - renderer.GetCurrentRegion()['w']) / renderer.width)
north = region['n'] + nsdist
south = region['s'] - nsdist
west = region['w'] - ewdist
east = region['e'] + ewdist
- renderer.GetRegion(n = north, s = south, w = west, e = east, update = True)
- self.mapdisplay.GetMapWindow().ZoomHistory(n = north, s = south, w = west, e = east)
-
+ renderer.GetRegion(
+ n=north, s=south, w=west, e=east, update=True)
+ self.mapdisplay.GetMapWindow().ZoomHistory(n=north, s=south, w=west, e=east)
+
if zoom:
self.mapdisplay.Map.AdjustRegion() # adjust resolution
- self.mapdisplay.Map.AlignExtentFromDisplay() # adjust extent
- self.mapdisplay.MapWindow.UpdateMap(render = True, renderVector = True)
+ self.mapdisplay.Map.AlignExtentFromDisplay() # adjust extent
+ self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)
else:
- self.mapdisplay.MapWindow.UpdateMap(render = False, renderVector = True)
-
- def AddQueryMapLayer(self, selectedOnly = True):
+ self.mapdisplay.MapWindow.UpdateMap(
+ render=False, renderVector=True)
+
+ def AddQueryMapLayer(self, selectedOnly=True):
"""Redraw a map
:return: True if map has been redrawn, False if no map is given
@@ -1695,15 +1846,19 @@
else:
fn = tlist.GetItems
- cats = { self.selLayer : fn() }
-
+ cats = {self.selLayer: fn()}
+
if self.mapdisplay.Map.GetLayerIndex(self.qlayer) < 0:
self.qlayer = None
-
+
if self.qlayer:
- self.qlayer.SetCmd(self.mapdisplay.AddTmpVectorMapLayer(self.dbMgrData['vectName'], cats, addLayer = False))
+ self.qlayer.SetCmd(
+ self.mapdisplay.AddTmpVectorMapLayer(
+ self.dbMgrData['vectName'],
+ cats, addLayer=False))
else:
- self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(self.dbMgrData['vectName'], cats)
+ self.qlayer = self.mapdisplay.AddTmpVectorMapLayer(
+ self.dbMgrData['vectName'], cats)
return self.qlayer
@@ -1721,7 +1876,10 @@
item = tlist.GetNextItem(item)
if item == -1:
break
- tlist.SetItemState(item, wx.LIST_STATE_SELECTED, wx.LIST_STATE_SELECTED)
+ tlist.SetItemState(
+ item,
+ wx.LIST_STATE_SELECTED,
+ wx.LIST_STATE_SELECTED)
event.Skip()
@@ -1734,21 +1892,21 @@
item = tlist.GetNextItem(item, wx.LIST_STATE_SELECTED)
if item == -1:
break
- tlist.SetItemState(item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
+ tlist.SetItemState(
+ item, 0, wx.LIST_STATE_SELECTED | wx.LIST_STATE_FOCUSED)
tlist.Focus(0)
-
+
event.Skip()
-
def OnDataDrawSelected(self, event):
"""Reload table description"""
- self._drawSelected(zoom = False)
+ self._drawSelected(zoom=False)
event.Skip()
def OnDataDrawSelectedZoom(self, event):
- self._drawSelected(zoom = True)
+ self._drawSelected(zoom=True)
event.Skip()
-
+
def OnExtractSelected(self, event):
"""Extract vector objects selected in attribute browse window
to new vector map
@@ -1757,32 +1915,33 @@
# cats = tlist.selectedCats[:]
cats = tlist.GetSelectedItems()
if len(cats) == 0:
- GMessage(parent = self,
- message = _('Nothing to extract.'))
+ GMessage(parent=self,
+ message=_('Nothing to extract.'))
return
else:
# dialog to get file name
- dlg = CreateNewVector(parent=self, title=_('Extract selected features'),
- giface=self.giface,
- cmd=(('v.extract',
- {'input': self.dbMgrData['vectName'],
- 'cats': ListOfCatsToRange(cats)},
- 'output')),
- disableTable=True)
+ dlg = CreateNewVector(
+ parent=self, title=_('Extract selected features'),
+ giface=self.giface,
+ cmd=(('v.extract',
+ {'input': self.dbMgrData['vectName'],
+ 'cats': ListOfCatsToRange(cats)},
+ 'output')),
+ disableTable=True)
if not dlg:
return
-
- name = dlg.GetName(full = True)
+ name = dlg.GetName(full=True)
+
if not self.mapdisplay and self.mapdisplay.tree:
- pass
+ pass
elif name and dlg.IsChecked('add'):
# add layer to map layer tree
- self.mapdisplay.tree.AddLayer(ltype = 'vector',
- lname = name,
- lcmd = ['d.vect', 'map=%s' % name])
+ self.mapdisplay.tree.AddLayer(ltype='vector',
+ lname=name,
+ lcmd=['d.vect', 'map=%s' % name])
dlg.Destroy()
-
+
def OnDeleteSelected(self, event):
"""Delete vector objects selected in attribute browse window
(attribures and geometry)
@@ -1790,9 +1949,9 @@
tlist = self.FindWindowById(self.layerPage[self.selLayer]['data'])
cats = tlist.GetSelectedItems()
if len(cats) == 0:
- GMessage(parent = self,
- message = _('Nothing to delete.'))
-
+ GMessage(parent=self,
+ message=_('Nothing to delete.'))
+
return
display = None
@@ -1800,44 +1959,49 @@
pass
elif 'vdigit' in self.mapdisplay.toolbars:
digitToolbar = self.mapdisplay.toolbars['vdigit']
- if digitToolbar and digitToolbar.GetLayer() and \
- digitToolbar.GetLayer().GetName() == self.dbMgrData['vectName']:
+ if digitToolbar and digitToolbar.GetLayer() and digitToolbar.GetLayer(
+ ).GetName() == self.dbMgrData['vectName']:
display = self.mapdisplay.GetMapWindow().GetDisplay()
- display.SetSelected(map(int, cats), layer = self.selLayer)
- self.mapdisplay.MapWindow.UpdateMap(render = True, renderVector = True)
-
+ display.SetSelected(map(int, cats), layer=self.selLayer)
+ self.mapdisplay.MapWindow.UpdateMap(
+ render=True, renderVector=True)
+
if self.OnDataItemDelete(None) and self.mapdisplay:
if display:
self.mapdisplay.GetMapWindow().digit.DeleteSelectedLines()
else:
RunCommand('v.edit',
- parent = self,
- quiet = True,
- map = self.dbMgrData['vectName'],
- tool = 'delete',
- cats = ListOfCatsToRange(cats))
-
- self.mapdisplay.MapWindow.UpdateMap(render = True, renderVector = True)
-
+ parent=self,
+ quiet=True,
+ map=self.dbMgrData['vectName'],
+ tool='delete',
+ cats=ListOfCatsToRange(cats))
+
+ self.mapdisplay.MapWindow.UpdateMap(render=True, renderVector=True)
+
def OnApplySqlStatement(self, event):
"""Apply simple/advanced sql statement"""
- keyColumn = -1 # index of key column
+ keyColumn = -1 # index of key column
listWin = self.FindWindowById(self.layerPage[self.selLayer]['data'])
sql = None
win = self.FindWindowById(self.layerPage[self.selLayer]['sqlNtb'])
if not win:
return
-
+
showSelected = False
wx.BeginBusyCursor()
if win.GetSelection() == 0:
# simple sql statement
- whereCol = self.FindWindowById(self.layerPage[self.selLayer]['whereColumn']).GetStringSelection()
- whereOpe = self.FindWindowById(self.layerPage[self.selLayer]['whereOperator']).GetStringSelection()
- whereWin = self.FindWindowById(self.layerPage[self.selLayer]['where'])
+ whereCol = self.FindWindowById(self.layerPage[self.selLayer][
+ 'whereColumn']).GetStringSelection()
+ whereOpe = self.FindWindowById(self.layerPage[self.selLayer][
+ 'whereOperator']).GetStringSelection()
+ whereWin = self.FindWindowById(
+ self.layerPage[self.selLayer]['where'])
whereVal = whereWin.GetValue().strip()
- table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
- if self.dbMgrData['mapDBInfo'].tables[table][whereCol]['ctype'] == str:
+ table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
+ if self.dbMgrData['mapDBInfo'].tables[
+ table][whereCol]['ctype'] == str:
# string attribute, check for quotes
whereVal = whereVal.replace('"', "'")
if whereVal:
@@ -1846,20 +2010,27 @@
if not whereVal.endswith("'"):
whereVal += "'"
whereWin.SetValue(whereVal)
-
+
try:
if len(whereVal) > 0:
showSelected = True
- keyColumn = listWin.LoadData(self.selLayer, where = whereCol + whereOpe + whereVal)
+ keyColumn = listWin.LoadData(
+ self.selLayer, where=whereCol + whereOpe + whereVal)
else:
keyColumn = listWin.LoadData(self.selLayer)
except GException as e:
- GError(parent = self,
- message = _("Loading attribute data failed.\n\n%s") % e.value)
- self.FindWindowById(self.layerPage[self.selLayer]['where']).SetValue('')
+ GError(
+ parent=self,
+ message=_("Loading attribute data failed.\n\n%s") %
+ e.value)
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['where']).SetValue('')
else:
# advanced sql statement
- win = self.FindWindowById(self.layerPage[self.selLayer]['statement'])
+ win = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['statement'])
try:
cols, where = self.ValidateSelectStatement(win.GetValue())
if cols is None and where is None:
@@ -1867,64 +2038,79 @@
if where:
showSelected = True
except TypeError:
- GError(parent = self,
- message = _("Loading attribute data failed.\n"
- "Invalid SQL select statement.\n\n%s") % win.GetValue())
- win.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
+ GError(
+ parent=self, message=_(
+ "Loading attribute data failed.\n"
+ "Invalid SQL select statement.\n\n%s") %
+ win.GetValue())
+ win.SetValue(
+ "SELECT * FROM %s" %
+ self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]['table'])
cols = None
where = None
-
+
if cols or where or sql:
try:
- keyColumn = listWin.LoadData(self.selLayer, columns = cols,
- where = where, sql = sql)
+ keyColumn = listWin.LoadData(self.selLayer, columns=cols,
+ where=where, sql=sql)
except GException as e:
- GError(parent = self,
- message = _("Loading attribute data failed.\n\n%s") % e.value)
- win.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
-
+ GError(
+ parent=self,
+ message=_("Loading attribute data failed.\n\n%s") %
+ e.value)
+ win.SetValue(
+ "SELECT * FROM %s" %
+ self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]['table'])
+
# sort by key column
if sql and 'order by' in sql.lower():
- pass # don't order by key column
+ pass # don't order by key column
else:
if keyColumn > -1:
- listWin.SortListItems(col = keyColumn, ascending = True)
+ listWin.SortListItems(col=keyColumn, ascending=True)
else:
- listWin.SortListItems(col = 0, ascending = True)
-
+ listWin.SortListItems(col=0, ascending=True)
+
wx.EndBusyCursor()
-
+
# update statusbar
- self.log.write(_("Number of loaded records: %d") % \
- self.FindWindowById(self.layerPage[self.selLayer]['data']).GetItemCount())
+ self.log.write(
+ _("Number of loaded records: %d") %
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['data']).GetItemCount())
# update map display if needed
if self.mapdisplay and \
- UserSettings.Get(group = 'atm', key = 'highlight', subkey = 'auto'):
+ UserSettings.Get(group='atm', key='highlight', subkey='auto'):
# TODO: replace by signals
if showSelected:
- self._drawSelected(zoom=False, selectedOnly=False)
+ self._drawSelected(zoom=False, selectedOnly=False)
else:
self.mapdisplay.RemoveQueryLayer()
- self.mapdisplay.MapWindow.UpdateMap(render=False) # TODO: replace by signals
+ self.mapdisplay.MapWindow.UpdateMap(
+ render=False) # TODO: replace by signals
- def OnBuilder(self,event):
+ def OnBuilder(self, event):
"""SQL Builder button pressed -> show the SQLBuilder dialog"""
if not self.builder:
- self.builder = SQLBuilderSelect(parent = self, id = wx.ID_ANY,
- vectmap = self.dbMgrData['vectName'],
- layer = self.selLayer,
- evtHandler = self.OnBuilderEvt)
+ self.builder = SQLBuilderSelect(parent=self, id=wx.ID_ANY,
+ vectmap=self.dbMgrData['vectName'],
+ layer=self.selLayer,
+ evtHandler=self.OnBuilderEvt)
self.builder.Show()
else:
self.builder.Raise()
-
+
def OnBuilderEvt(self, event):
if event == 'apply':
sqlstr = self.builder.GetSQLStatement()
- self.FindWindowById(self.layerPage[self.selLayer]['statement']).SetValue(sqlstr)
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'statement']).SetValue(sqlstr)
# apply query
- #self.listOfSQLStatements.append(sqlstr) #TODO probably it was bug
+ # self.listOfSQLStatements.append(sqlstr) #TODO probably it was bug
self.OnApplySqlStatement(None)
# close builder on apply
if self.builder.CloseOnApply():
@@ -1940,7 +2126,7 @@
"""
if statement[0:7].lower() != 'select ':
return None
-
+
cols = ''
index = 7
for c in statement[index:]:
@@ -1952,26 +2138,28 @@
cols = None
else:
cols = cols.split(',')
-
- tablelen = len(self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table'])
-
- if statement[index+1:index+6].lower() != 'from ' or \
- statement[index+6:index+6+tablelen] != '%s' % \
+
+ tablelen = len(
+ self.dbMgrData['mapDBInfo'].layers[
+ self.selLayer]['table'])
+
+ if statement[index + 1:index + 6].lower() != 'from ' or \
+ statement[index + 6:index + 6 + tablelen] != '%s' % \
(self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']):
return None
-
- if len(statement[index+7+tablelen:]) > 0:
+
+ if len(statement[index + 7 + tablelen:]) > 0:
index = statement.lower().find('where ')
if index > -1:
- where = statement[index+6:]
+ where = statement[index + 6:]
else:
where = None
else:
where = None
-
+
return (cols, where)
- def LoadData(self, layer, columns = None, where = None, sql = None):
+ def LoadData(self, layer, columns=None, where=None, sql=None):
"""Load data into list
:param int layer: layer number
@@ -1979,7 +2167,7 @@
:param str where: where statement
:param str sql: full sql statement
- :return: id of key column
+ :return: id of key column
:return: -1 if key column is not displayed
"""
listWin = self.FindWindowById(self.layerPage[layer]['data'])
@@ -1998,27 +2186,33 @@
return
win = self.FindWindowById(self.layerPage[self.selLayer]['sqlNtb'])
if win.GetSelection() == 0:
- self.FindWindowById(self.layerPage[layer]['whereColumn']).SetSelection(0)
- self.FindWindowById(self.layerPage[layer]['whereOperator']).SetSelection(0)
+ self.FindWindowById(
+ self.layerPage[layer]['whereColumn']).SetSelection(0)
+ self.FindWindowById(
+ self.layerPage[layer]['whereOperator']).SetSelection(0)
self.FindWindowById(self.layerPage[layer]['where']).SetValue('')
else:
- sqlWin = self.FindWindowById(self.layerPage[self.selLayer]['statement'])
- sqlWin.SetValue("SELECT * FROM %s" % self.dbMgrData['mapDBInfo'].layers[layer]['table'])
-
+ sqlWin = self.FindWindowById(
+ self.layerPage[self.selLayer]['statement'])
+ sqlWin.SetValue("SELECT * FROM %s" %
+ self.dbMgrData['mapDBInfo'].layers[layer]['table'])
+
self.UpdatePage(layer)
-
-class DbMgrTablesPage(DbMgrNotebookBase):
- def __init__(self, parent, parentDbMgrBase, onlyLayer = -1):
+
+
+class DbMgrTablesPage(DbMgrNotebookBase):
+
+ def __init__(self, parent, parentDbMgrBase, onlyLayer=-1):
"""Page for managing tables
:param parent: GUI parent
:param parentDbMgrBase: instance of DbMgrBase class
:param onlyLayer: create only tab of given layer, if -1
- creates tabs of all layers
+ creates tabs of all layers
"""
- DbMgrNotebookBase.__init__(self, parent = parent,
- parentDbMgrBase = parentDbMgrBase)
+ DbMgrNotebookBase.__init__(self, parent=parent,
+ parentDbMgrBase=parentDbMgrBase)
for layer in self.dbMgrData['mapDBInfo'].layers.keys():
if onlyLayer > 0 and layer != onlyLayer:
@@ -2026,26 +2220,26 @@
self.AddLayer(layer)
if self.layers:
- self.SetSelection(0) # select first layer
+ self.SetSelection(0) # select first layer
self.selLayer = self.layers[0]
- def AddLayer(self, layer, pos = -1):
- """Adds tab which represents table
+ def AddLayer(self, layer, pos=-1):
+ """Adds tab which represents table
:param layer: vector map layer connected to table
:param pos: position of tab, if -1 it is added to end
- :return: True if layer was added
- :return: False if layer was not added - layer has been already added or does not exist
+ :return: True if layer was added
+ :return: False if layer was not added - layer has been already added or does not exist
"""
if layer in self.layers or \
- layer not in self.parentDbMgrBase.GetVectorLayers():
+ layer not in self.parentDbMgrBase.GetVectorLayers():
return False
- self.layers.append(layer)
+ self.layers.append(layer)
self.layerPage[layer] = {}
- panel = wx.Panel(parent = self, id = wx.ID_ANY)
+ panel = wx.Panel(parent=self, id=wx.ID_ANY)
self.layerPage[layer]['tablePage'] = panel.GetId()
label = _("Table")
if not self.dbMgrData['editable']:
@@ -2053,162 +2247,198 @@
if pos == -1:
pos = self.GetPageCount()
- self.InsertPage(pos, page = panel,
- text = " %d / %s %s" % (layer, label,
- self.dbMgrData['mapDBInfo'].layers[layer]['table']))
-
+ self.InsertPage(
+ pos, page=panel, text=" %d / %s %s" %
+ (layer, label, self.dbMgrData['mapDBInfo'].layers[layer]['table']))
+
pageSizer = wx.BoxSizer(wx.VERTICAL)
-
+
#
# dbInfo
#
- dbBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
- label = " %s " % _("Database connection"))
+ dbBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+ label=" %s " % _("Database connection"))
dbSizer = wx.StaticBoxSizer(dbBox, wx.VERTICAL)
- dbSizer.Add(item = CreateDbInfoDesc(panel, self.dbMgrData['mapDBInfo'], layer),
- proportion = 1,
- flag = wx.EXPAND | wx.ALL,
- border = 3)
-
+ dbSizer.Add(
+ item=CreateDbInfoDesc(
+ panel,
+ self.dbMgrData['mapDBInfo'],
+ layer),
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
+
#
# table description
#
table = self.dbMgrData['mapDBInfo'].layers[layer]['table']
- tableBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
- label = " %s " % _("Table <%s> - right-click to delete column(s)") % table)
-
+ tableBox = wx.StaticBox(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=" %s " %
+ _("Table <%s> - right-click to delete column(s)") %
+ table)
+
tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
-
+
tlist = self._createTableDesc(panel, table)
- tlist.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp) #wxMSW
- tlist.Bind(wx.EVT_RIGHT_UP, self.OnTableRightUp) #wxGTK
+ tlist.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnTableRightUp) # wxMSW
+ tlist.Bind(wx.EVT_RIGHT_UP, self.OnTableRightUp) # wxGTK
self.layerPage[layer]['tableData'] = tlist.GetId()
-
+
# manage columns (add)
- addBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
- label = " %s " % _("Add column"))
+ addBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+ label=" %s " % _("Add column"))
addSizer = wx.StaticBoxSizer(addBox, wx.HORIZONTAL)
-
- column = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = '',
- size = (150, -1), style = wx.TE_PROCESS_ENTER)
- column.Bind(wx.EVT_TEXT, self.OnTableAddColumnName)
+
+ column = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
+ size=(150, -1), style=wx.TE_PROCESS_ENTER)
+ column.Bind(wx.EVT_TEXT, self.OnTableAddColumnName)
column.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemAdd)
self.layerPage[layer]['addColName'] = column.GetId()
- addSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Column")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = column, proportion = 1,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
- ctype = wx.Choice (parent = panel, id = wx.ID_ANY,
- choices = ["integer",
- "double",
- "varchar",
- "date"]) # FIXME
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Column")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=column, proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
+ ctype = wx.Choice(parent=panel, id=wx.ID_ANY,
+ choices=["integer",
+ "double",
+ "varchar",
+ "date"]) # FIXME
ctype.SetSelection(0)
ctype.Bind(wx.EVT_CHOICE, self.OnTableChangeType)
self.layerPage[layer]['addColType'] = ctype.GetId()
- addSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Type")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = ctype,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
- length = wx.SpinCtrl(parent = panel, id = wx.ID_ANY, size = (65, -1),
- initial = 250,
- min = 1, max = 1e6)
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Type")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=ctype,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
+ length = wx.SpinCtrl(parent=panel, id=wx.ID_ANY, size=(65, -1),
+ initial=250,
+ min=1, max=1e6)
length.Enable(False)
self.layerPage[layer]['addColLength'] = length.GetId()
- addSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Length")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = length,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
- btnAddCol = wx.Button(parent = panel, id = wx.ID_ANY, label = _("Add"))
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Length")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=length,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
+ btnAddCol = wx.Button(parent=panel, id=wx.ID_ANY, label=_("Add"))
btnAddCol.Bind(wx.EVT_BUTTON, self.OnTableItemAdd)
btnAddCol.Enable(False)
self.layerPage[layer]['addColButton'] = btnAddCol.GetId()
- addSizer.Add(item = btnAddCol, flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
- border = 3)
-
+ addSizer.Add(item=btnAddCol, flag=wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
+ border=3)
+
# manage columns (rename)
- renameBox = wx.StaticBox(parent = panel, id = wx.ID_ANY,
- label = " %s " % _("Rename column"))
+ renameBox = wx.StaticBox(parent=panel, id=wx.ID_ANY,
+ label=" %s " % _("Rename column"))
renameSizer = wx.StaticBoxSizer(renameBox, wx.HORIZONTAL)
-
- columnFrom = wx.ComboBox(parent = panel, id = wx.ID_ANY, size = (150, -1),
- style = wx.CB_SIMPLE | wx.CB_READONLY,
- choices = self.dbMgrData['mapDBInfo'].GetColumns(table))
+
+ columnFrom = wx.ComboBox(
+ parent=panel, id=wx.ID_ANY, size=(150, -1),
+ style=wx.CB_SIMPLE | wx.CB_READONLY,
+ choices=self.dbMgrData['mapDBInfo'].GetColumns(table))
columnFrom.SetSelection(0)
self.layerPage[layer]['renameCol'] = columnFrom.GetId()
- renameSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("Column")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- renameSizer.Add(item = columnFrom, proportion = 1,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
- columnTo = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = '',
- size = (150, -1), style = wx.TE_PROCESS_ENTER)
- columnTo.Bind(wx.EVT_TEXT, self.OnTableRenameColumnName)
+ renameSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Column")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ renameSizer.Add(item=columnFrom, proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
+ columnTo = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value='',
+ size=(150, -1), style=wx.TE_PROCESS_ENTER)
+ columnTo.Bind(wx.EVT_TEXT, self.OnTableRenameColumnName)
columnTo.Bind(wx.EVT_TEXT_ENTER, self.OnTableItemChange)
self.layerPage[layer]['renameColTo'] = columnTo.GetId()
- renameSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY, label = _("To")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- renameSizer.Add(item = columnTo, proportion = 1,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
- btnRenameCol = wx.Button(parent = panel, id = wx.ID_ANY, label = _("&Rename"))
+ renameSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("To")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ renameSizer.Add(item=columnTo, proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
+ btnRenameCol = wx.Button(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("&Rename"))
btnRenameCol.Bind(wx.EVT_BUTTON, self.OnTableItemChange)
btnRenameCol.Enable(False)
self.layerPage[layer]['renameColButton'] = btnRenameCol.GetId()
- renameSizer.Add(item = btnRenameCol, flag = wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
- border = 3)
-
- tableSizer.Add(item = tlist,
- flag = wx.ALL | wx.EXPAND,
- proportion = 1,
- border = 3)
-
+ renameSizer.Add(
+ item=btnRenameCol,
+ flag=wx.ALL | wx.ALIGN_RIGHT | wx.EXPAND,
+ border=3)
+
+ tableSizer.Add(item=tlist,
+ flag=wx.ALL | wx.EXPAND,
+ proportion=1,
+ border=3)
+
pageSizer.Add(item=dbSizer,
- flag = wx.ALL | wx.EXPAND,
- proportion = 0,
- border = 3)
-
- pageSizer.Add(item = tableSizer,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
- proportion = 1,
- border = 3)
-
- pageSizer.Add(item = addSizer,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
- proportion = 0,
- border = 3)
- pageSizer.Add(item = renameSizer,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
- proportion = 0,
- border = 3)
-
+ flag=wx.ALL | wx.EXPAND,
+ proportion=0,
+ border=3)
+
+ pageSizer.Add(item=tableSizer,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ proportion=1,
+ border=3)
+
+ pageSizer.Add(item=addSizer,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ proportion=0,
+ border=3)
+ pageSizer.Add(item=renameSizer,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ proportion=0,
+ border=3)
+
panel.SetSizer(pageSizer)
-
+
if not self.dbMgrData['editable']:
- for widget in [columnTo, columnFrom, length, ctype,
- column, btnAddCol, btnRenameCol]:
+ for widget in [columnTo, columnFrom, length, ctype,
+ column, btnAddCol, btnRenameCol]:
widget.Enable(False)
return True
def _createTableDesc(self, parent, table):
"""Create list with table description"""
- tlist = TableListCtrl(parent = parent, id = wx.ID_ANY,
- table = self.dbMgrData['mapDBInfo'].tables[table],
- columns = self.dbMgrData['mapDBInfo'].GetColumns(table))
+ tlist = TableListCtrl(
+ parent=parent,
+ id=wx.ID_ANY,
+ table=self.dbMgrData['mapDBInfo'].tables[table],
+ columns=self.dbMgrData['mapDBInfo'].GetColumns(table))
tlist.Populate()
# sorter
# itemDataMap = list.Populate()
@@ -2219,7 +2449,9 @@
def OnTableChangeType(self, event):
"""Data type for new column changed. Enable or disable
data length widget"""
- win = self.FindWindowById(self.layerPage[self.selLayer]['addColLength'])
+ win = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['addColLength'])
if event.GetString() == "varchar":
win.Enable(True)
else:
@@ -2227,9 +2459,13 @@
def OnTableRenameColumnName(self, event):
"""Editing column name to be added to the table"""
- btn = self.FindWindowById(self.layerPage[self.selLayer]['renameColButton'])
- col = self.FindWindowById(self.layerPage[self.selLayer]['renameCol'])
- colTo = self.FindWindowById(self.layerPage[self.selLayer]['renameColTo'])
+ btn = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameColButton'])
+ col = self.FindWindowById(self.layerPage[self.selLayer]['renameCol'])
+ colTo = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameColTo'])
if len(col.GetValue()) > 0 and len(colTo.GetValue()) > 0:
btn.Enable(True)
else:
@@ -2239,7 +2475,9 @@
def OnTableAddColumnName(self, event):
"""Editing column name to be added to the table"""
- btn = self.FindWindowById(self.layerPage[self.selLayer]['addColButton'])
+ btn = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['addColButton'])
if len(event.GetString()) > 0:
btn.Enable(True)
else:
@@ -2249,50 +2487,61 @@
def OnTableItemChange(self, event):
"""Rename column in the table"""
- tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
- name = self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).GetValue()
- nameTo = self.FindWindowById(self.layerPage[self.selLayer]['renameColTo']).GetValue()
+ tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
+ name = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameCol']).GetValue()
+ nameTo = self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameColTo']).GetValue()
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]["table"]
if not name or not nameTo:
- GError(parent = self,
- message = _("Unable to rename column. "
- "No column name defined."))
+ GError(parent=self,
+ message=_("Unable to rename column. "
+ "No column name defined."))
return
else:
- item = tlist.FindItem(start = -1, str = name)
+ item = tlist.FindItem(start=-1, str=name)
if item > -1:
- if tlist.FindItem(start = -1, str = nameTo) > -1:
- GError(parent = self,
- message = _("Unable to rename column <%(column)s> to "
- "<%(columnTo)s>. Column already exists "
- "in the table <%(table)s>.") % \
- {'column' : name, 'columnTo' : nameTo,
- 'table' : table})
+ if tlist.FindItem(start=-1, str=nameTo) > -1:
+ GError(parent=self,
+ message=_("Unable to rename column <%(column)s> to "
+ "<%(columnTo)s>. Column already exists "
+ "in the table <%(table)s>.") %
+ {'column': name, 'columnTo': nameTo,
+ 'table': table})
return
else:
tlist.SetItemText(item, nameTo)
self.listOfCommands.append(('v.db.renamecolumn',
- { 'map' : self.dbMgrData['vectName'],
- 'layer' : self.selLayer,
- 'column' : '%s,%s' % (name, nameTo) }
+ {'map': self.dbMgrData['vectName'],
+ 'layer': self.selLayer,
+ 'column': '%s,%s' % (name, nameTo)}
))
else:
- GError(parent = self,
- message = _("Unable to rename column. "
- "Column <%(column)s> doesn't exist in the table <%(table)s>.") %
- {'column' : name, 'table' : table})
+ GError(
+ parent=self,
+ message=_(
+ "Unable to rename column. "
+ "Column <%(column)s> doesn't exist in the table <%(table)s>.") % {
+ 'column': name,
+ 'table': table})
return
-
+
# apply changes
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
# update widgets
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
- self.FindWindowById(self.layerPage[self.selLayer]['renameColTo']).SetValue('')
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameCol']).SetItems(
+ self.dbMgrData['mapDBInfo'].GetColumns(table))
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameCol']).SetSelection(0)
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameColTo']).SetValue('')
event.Skip()
@@ -2302,20 +2551,27 @@
self.popupTableID1 = wx.NewId()
self.popupTableID2 = wx.NewId()
self.popupTableID3 = wx.NewId()
- self.Bind(wx.EVT_MENU, self.OnTableItemDelete, id = self.popupTableID1)
- self.Bind(wx.EVT_MENU, self.OnTableItemDeleteAll, id = self.popupTableID2)
- self.Bind(wx.EVT_MENU, self.OnTableReload, id = self.popupTableID3)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnTableItemDelete,
+ id=self.popupTableID1)
+ self.Bind(
+ wx.EVT_MENU,
+ self.OnTableItemDeleteAll,
+ id=self.popupTableID2)
+ self.Bind(wx.EVT_MENU, self.OnTableReload, id=self.popupTableID3)
# generate popup-menu
menu = wx.Menu()
menu.Append(self.popupTableID1, _("Drop selected column"))
- if self.FindWindowById(self.layerPage[self.selLayer]['tableData']).GetFirstSelected() == -1:
+ if self.FindWindowById(self.layerPage[self.selLayer][
+ 'tableData']).GetFirstSelected() == -1:
menu.Enable(self.popupTableID1, False)
menu.Append(self.popupTableID2, _("Drop all columns"))
menu.AppendSeparator()
menu.Append(self.popupTableID3, _("Reload"))
-
- if not self.dbMgrData['editable']:
+
+ if not self.dbMgrData['editable']:
menu.Enable(self.popupTableID1, False)
menu.Enable(self.popupTableID2, False)
@@ -2325,10 +2581,11 @@
def OnTableItemDelete(self, event):
"""Delete selected item(s) from the list"""
tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
-
+
item = tlist.GetFirstSelected()
countSelected = tlist.GetSelectedItemCount()
- if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
+ if UserSettings.Get(
+ group='atm', key='askOnDeleteRec', subkey='enabled'):
# if the user select more columns to delete, all the columns name
# will appear the the warning dialog
if tlist.GetSelectedItemCount() > 1:
@@ -2339,102 +2596,127 @@
deleteColumns += ", '%s'" % tlist.GetItemText(item)
else:
deleteColumns = "column '%s'" % tlist.GetItemText(item)
- deleteDialog = wx.MessageBox(parent = self,
- message = _("Selected %s will PERMANENTLY removed "
- "from table. Do you want to drop the column?") % \
- (deleteColumns),
- caption = _("Drop column(s)"),
- style = wx.YES_NO | wx.CENTRE)
+ deleteDialog = wx.MessageBox(
+ parent=self,
+ message=_(
+ "Selected %s will PERMANENTLY removed "
+ "from table. Do you want to drop the column?") %
+ (deleteColumns),
+ caption=_("Drop column(s)"),
+ style=wx.YES_NO | wx.CENTRE)
if deleteDialog != wx.YES:
return False
item = tlist.GetFirstSelected()
while item != -1:
self.listOfCommands.append(('v.db.dropcolumn',
- { 'map' : self.dbMgrData['vectName'],
- 'layer' : self.selLayer,
- 'column' : tlist.GetItemText(item) }
+ {'map': self.dbMgrData['vectName'],
+ 'layer': self.selLayer,
+ 'column': tlist.GetItemText(item)}
))
tlist.DeleteItem(item)
item = tlist.GetFirstSelected()
-
+
# apply changes
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
-
+
# update widgets
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
-
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameCol']).SetItems(
+ self.dbMgrData['mapDBInfo'].GetColumns(table))
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameCol']).SetSelection(0)
+
event.Skip()
def OnTableItemDeleteAll(self, event):
"""Delete all items from the list"""
- table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
- cols = self.dbMgrData['mapDBInfo'].GetColumns(table)
+ table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
+ cols = self.dbMgrData['mapDBInfo'].GetColumns(table)
keyColumn = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['key']
if keyColumn in cols:
cols.remove(keyColumn)
-
- if UserSettings.Get(group = 'atm', key = 'askOnDeleteRec', subkey = 'enabled'):
- deleteDialog = wx.MessageBox(parent = self,
- message = _("Selected columns\n%s\nwill PERMANENTLY removed "
- "from table. Do you want to drop the columns?") % \
- ('\n'.join(cols)),
- caption = _("Drop column(s)"),
- style = wx.YES_NO | wx.CENTRE)
+
+ if UserSettings.Get(
+ group='atm', key='askOnDeleteRec', subkey='enabled'):
+ deleteDialog = wx.MessageBox(
+ parent=self,
+ message=_(
+ "Selected columns\n%s\nwill PERMANENTLY removed "
+ "from table. Do you want to drop the columns?") %
+ ('\n'.join(cols)),
+ caption=_("Drop column(s)"),
+ style=wx.YES_NO | wx.CENTRE)
if deleteDialog != wx.YES:
return False
-
+
for col in cols:
self.listOfCommands.append(('v.db.dropcolumn',
- { 'map' : self.dbMgrData['vectName'],
- 'layer' : self.selLayer,
- 'column' : col }
+ {'map': self.dbMgrData['vectName'],
+ 'layer': self.selLayer,
+ 'column': col}
))
- self.FindWindowById(self.layerPage[self.selLayer]['tableData']).DeleteAllItems()
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'tableData']).DeleteAllItems()
# apply changes
self.ApplyCommands(self.listOfCommands, self.listOfSQLStatements)
# update widgets
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameCol']).SetItems(
+ self.dbMgrData['mapDBInfo'].GetColumns(table))
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameCol']).SetSelection(0)
event.Skip()
- def OnTableReload(self, event = None):
+ def OnTableReload(self, event=None):
"""Reload table description"""
- self.FindWindowById(self.layerPage[self.selLayer]['tableData']).Populate(update = True)
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['tableData']).Populate(
+ update=True)
self.listOfCommands = []
def OnTableItemAdd(self, event):
"""Add new column to the table"""
- name = self.FindWindowById(self.layerPage[self.selLayer]['addColName']).GetValue()
-
- ctype = self.FindWindowById(self.layerPage[self.selLayer]['addColType']). \
- GetStringSelection()
-
- length = int(self.FindWindowById(self.layerPage[self.selLayer]['addColLength']). \
- GetValue())
-
+ name = self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['addColName']).GetValue()
+
+ ctype = self.FindWindowById(self.layerPage[self.selLayer][
+ 'addColType']). GetStringSelection()
+
+ length = int(
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['addColLength']). GetValue())
+
# add item to the list of table columns
tlist = self.FindWindowById(self.layerPage[self.selLayer]['tableData'])
-
- index = tlist.InsertStringItem(sys.maxint, str(name))
+ index = tlist.InsertStringItem(sys.maxsize, str(name))
tlist.SetStringItem(index, 0, str(name))
tlist.SetStringItem(index, 1, str(ctype))
tlist.SetStringItem(index, 2, str(length))
-
+
self.AddColumn(name, ctype, length)
# update widgets
table = self.dbMgrData['mapDBInfo'].layers[self.selLayer]['table']
- self.FindWindowById(self.layerPage[self.selLayer]['addColName']).SetValue('')
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetItems(self.dbMgrData['mapDBInfo'].GetColumns(table))
- self.FindWindowById(self.layerPage[self.selLayer]['renameCol']).SetSelection(0)
-
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'addColName']).SetValue('')
+ self.FindWindowById(
+ self.layerPage[
+ self.selLayer]['renameCol']).SetItems(
+ self.dbMgrData['mapDBInfo'].GetColumns(table))
+ self.FindWindowById(self.layerPage[self.selLayer][
+ 'renameCol']).SetSelection(0)
+
event.Skip()
def UpdatePage(self, layer):
@@ -2444,86 +2726,90 @@
# update table description
tlist = self.FindWindowById(self.layerPage[layer]['tableData'])
- tlist.Update(table = self.dbMgrData['mapDBInfo'].tables[table],
- columns = self.dbMgrData['mapDBInfo'].GetColumns(table))
+ tlist.Update(table=self.dbMgrData['mapDBInfo'].tables[table],
+ columns=self.dbMgrData['mapDBInfo'].GetColumns(table))
self.OnTableReload(None)
+
class DbMgrLayersPage(wx.Panel):
+
def __init__(self, parent, parentDbMgrBase):
"""Create layer manage page"""
self.parentDbMgrBase = parentDbMgrBase
self.dbMgrData = self.parentDbMgrBase.dbMgrData
- wx.Panel.__init__(self, parent = parent)
- splitterWin = wx.SplitterWindow(parent = self, id = wx.ID_ANY)
+ wx.Panel.__init__(self, parent=parent)
+ splitterWin = wx.SplitterWindow(parent=self, id=wx.ID_ANY)
splitterWin.SetMinimumPaneSize(100)
-
+
#
# list of layers
#
- panelList = wx.Panel(parent = splitterWin, id = wx.ID_ANY)
+ panelList = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
- panelListSizer = wx.BoxSizer(wx.VERTICAL)
- layerBox = wx.StaticBox(parent = panelList, id = wx.ID_ANY,
- label = " %s " % _("List of layers"))
+ panelListSizer = wx.BoxSizer(wx.VERTICAL)
+ layerBox = wx.StaticBox(parent=panelList, id=wx.ID_ANY,
+ label=" %s " % _("List of layers"))
layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
self.layerList = self._createLayerDesc(panelList)
- self.layerList.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnLayerRightUp) #wxMSW
- self.layerList.Bind(wx.EVT_RIGHT_UP, self.OnLayerRightUp) #wxGTK
-
- layerSizer.Add(item = self.layerList,
- flag = wx.ALL | wx.EXPAND,
- proportion = 1,
- border = 3)
+ self.layerList.Bind(
+ wx.EVT_COMMAND_RIGHT_CLICK,
+ self.OnLayerRightUp) # wxMSW
+ self.layerList.Bind(wx.EVT_RIGHT_UP, self.OnLayerRightUp) # wxGTK
- panelListSizer.Add(item = layerSizer,
- flag = wx.ALL | wx.EXPAND,
- proportion = 1,
- border = 3)
+ layerSizer.Add(item=self.layerList,
+ flag=wx.ALL | wx.EXPAND,
+ proportion=1,
+ border=3)
+ panelListSizer.Add(item=layerSizer,
+ flag=wx.ALL | wx.EXPAND,
+ proportion=1,
+ border=3)
+
panelList.SetSizer(panelListSizer)
#
# manage part
#
- panelManage = wx.Panel(parent = splitterWin, id = wx.ID_ANY)
-
+ panelManage = wx.Panel(parent=splitterWin, id=wx.ID_ANY)
+
manageSizer = wx.BoxSizer(wx.VERTICAL)
- self.manageLayerBook = LayerBook(parent = panelManage, id = wx.ID_ANY,
- parentDialog = self)
+ self.manageLayerBook = LayerBook(parent=panelManage, id=wx.ID_ANY,
+ parentDialog=self)
if not self.dbMgrData['editable']:
self.manageLayerBook.Enable(False)
- manageSizer.Add(item = self.manageLayerBook,
- proportion = 1,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
- border = 5)
+ manageSizer.Add(item=self.manageLayerBook,
+ proportion=1,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ border=5)
- panelSizer = wx.BoxSizer(wx.VERTICAL)
- panelSizer.Add(item = splitterWin,
- proportion = 1,
- flag = wx.EXPAND)
+ panelSizer = wx.BoxSizer(wx.VERTICAL)
+ panelSizer.Add(item=splitterWin,
+ proportion=1,
+ flag=wx.EXPAND)
panelManage.SetSizer(manageSizer)
- splitterWin.SplitHorizontally(panelList, panelManage, 100)
+ splitterWin.SplitHorizontally(panelList, panelManage, 100)
splitterWin.Fit()
self.SetSizer(panelSizer)
def _createLayerDesc(self, parent):
"""Create list of linked layers"""
- tlist = LayerListCtrl(parent = parent, id = wx.ID_ANY,
- layers = self.dbMgrData['mapDBInfo'].layers)
-
+ tlist = LayerListCtrl(parent=parent, id=wx.ID_ANY,
+ layers=self.dbMgrData['mapDBInfo'].layers)
+
tlist.Populate()
# sorter
# itemDataMap = list.Populate()
# listmix.ColumnSorterMixin.__init__(self, 2)
return tlist
-
- def UpdatePage(self):
+
+ def UpdatePage(self):
#
# 'manage layers' page
#
@@ -2532,45 +2818,50 @@
#self.dbMgrData['mapDBInfo'] = VectorDBInfo(self.dbMgrData['vectName'])
self.layerList.Update(self.dbMgrData['mapDBInfo'].layers)
- self.layerList.Populate(update = True)
+ self.layerList.Populate(update=True)
# update selected widgets
listOfLayers = map(str, self.dbMgrData['mapDBInfo'].layers.keys())
- ### delete layer page
+ # delete layer page
self.manageLayerBook.deleteLayer.SetItems(listOfLayers)
if len(listOfLayers) > 0:
- self.manageLayerBook.deleteLayer.SetStringSelection(listOfLayers[0])
- tableName = self.dbMgrData['mapDBInfo'].layers[int(listOfLayers[0])]['table']
+ self.manageLayerBook.deleteLayer.SetStringSelection(
+ listOfLayers
+ [0])
+ tableName = self.dbMgrData['mapDBInfo'].layers[int(listOfLayers[0])][
+ 'table']
maxLayer = max(self.dbMgrData['mapDBInfo'].layers.keys())
else:
tableName = ''
maxLayer = 0
- self.manageLayerBook.deleteTable.SetLabel( \
- _('Drop also linked attribute table (%s)') % \
- tableName)
- ### add layer page
- self.manageLayerBook.addLayerWidgets['layer'][1].SetValue(\
- maxLayer+1)
- ### modify layer
- self.manageLayerBook.modifyLayerWidgets['layer'][1].SetItems(listOfLayers)
- self.manageLayerBook.OnChangeLayer(event = None)
+ self.manageLayerBook.deleteTable.SetLabel(
+ _('Drop also linked attribute table (%s)') %
+ tableName)
+ # add layer page
+ self.manageLayerBook.addLayerWidgets['layer'][1].SetValue(
+ maxLayer + 1)
+ # modify layer
+ self.manageLayerBook.modifyLayerWidgets[
+ 'layer'][1].SetItems(listOfLayers)
+ self.manageLayerBook.OnChangeLayer(event=None)
def OnLayerRightUp(self, event):
"""Layer description area, context menu"""
pass
+
class TableListCtrl(wx.ListCtrl,
listmix.ListCtrlAutoWidthMixin):
# listmix.TextEditMixin):
"""Table description list"""
- def __init__(self, parent, id, table, columns, pos = wx.DefaultPosition,
- size = wx.DefaultSize):
+ def __init__(self, parent, id, table, columns, pos=wx.DefaultPosition,
+ size=wx.DefaultSize):
- self.parent = parent
- self.table = table
+ self.parent = parent
+ self.table = table
self.columns = columns
wx.ListCtrl.__init__(self, parent, id, pos, size,
- style = wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+ style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
wx.BORDER_NONE)
listmix.ListCtrlAutoWidthMixin.__init__(self)
@@ -2578,27 +2869,27 @@
def Update(self, table, columns):
"""Update column description"""
- self.table = table
+ self.table = table
self.columns = columns
- def Populate(self, update = False):
+ def Populate(self, update=False):
"""Populate the list"""
- itemData = {} # requested by sorter
+ itemData = {} # requested by sorter
if not update:
headings = [_("Column name"), _("Data type"), _("Data length")]
i = 0
for h in headings:
- self.InsertColumn(col = i, heading = h)
+ self.InsertColumn(col=i, heading=h)
i += 1
- self.SetColumnWidth(col = 0, width = 350)
- self.SetColumnWidth(col = 1, width = 175)
+ self.SetColumnWidth(col=0, width=350)
+ self.SetColumnWidth(col=1, width=175)
else:
self.DeleteAllItems()
i = 0
for column in self.columns:
- index = self.InsertStringItem(sys.maxint, str(column))
+ index = self.InsertStringItem(sys.maxsize, str(column))
self.SetStringItem(index, 0, str(column))
self.SetStringItem(index, 1, str(self.table[column]['type']))
self.SetStringItem(index, 2, str(self.table[column]['length']))
@@ -2609,9 +2900,10 @@
i = i + 1
self.SendSizeEvent()
-
+
return itemData
+
class LayerListCtrl(wx.ListCtrl,
listmix.ListCtrlAutoWidthMixin):
# listmix.ColumnSorterMixin):
@@ -2619,13 +2911,13 @@
"""Layer description list"""
def __init__(self, parent, id, layers,
- pos = wx.DefaultPosition,
- size = wx.DefaultSize):
+ pos=wx.DefaultPosition,
+ size=wx.DefaultSize):
self.parent = parent
self.layers = layers
wx.ListCtrl.__init__(self, parent, id, pos, size,
- style = wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
+ style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_VRULES |
wx.BORDER_NONE)
listmix.ListCtrlAutoWidthMixin.__init__(self)
@@ -2635,27 +2927,32 @@
"""Update description"""
self.layers = layers
- def Populate(self, update = False):
+ def Populate(self, update=False):
"""Populate the list"""
- itemData = {} # requested by sorter
+ itemData = {} # requested by sorter
if not update:
- headings = [_("Layer"), _("Driver"), _("Database"), _("Table"), _("Key")]
+ headings = [
+ _("Layer"),
+ _("Driver"),
+ _("Database"),
+ _("Table"),
+ _("Key")]
i = 0
for h in headings:
- self.InsertColumn(col = i, heading = h)
+ self.InsertColumn(col=i, heading=h)
i += 1
else:
self.DeleteAllItems()
i = 0
for layer in self.layers.keys():
- index = self.InsertStringItem(sys.maxint, str(layer))
+ index = self.InsertStringItem(sys.maxsize, str(layer))
self.SetStringItem(index, 0, str(layer))
database = str(self.layers[layer]['database'])
- driver = str(self.layers[layer]['driver'])
- table = str(self.layers[layer]['table'])
- key = str(self.layers[layer]['key'])
+ driver = str(self.layers[layer]['driver'])
+ table = str(self.layers[layer]['table'])
+ key = str(self.layers[layer]['key'])
self.SetStringItem(index, 1, driver)
self.SetStringItem(index, 2, database)
self.SetStringItem(index, 3, table)
@@ -2669,63 +2966,66 @@
i += 1
for i in range(self.GetColumnCount()):
- self.SetColumnWidth(col = i, width = wx.LIST_AUTOSIZE)
- if self.GetColumnWidth(col = i) < 60:
- self.SetColumnWidth(col = i, width = 60)
+ self.SetColumnWidth(col=i, width=wx.LIST_AUTOSIZE)
+ if self.GetColumnWidth(col=i) < 60:
+ self.SetColumnWidth(col=i, width=60)
self.SendSizeEvent()
-
+
return itemData
+
class LayerBook(wx.Notebook):
"""Manage layers (add, delete, modify)"""
+
def __init__(self, parent, id,
parentDialog,
- style = wx.BK_DEFAULT):
- wx.Notebook.__init__(self, parent, id, style = style)
+ style=wx.BK_DEFAULT):
+ wx.Notebook.__init__(self, parent, id, style=style)
- self.parent = parent
+ self.parent = parent
self.parentDialog = parentDialog
- self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
+ self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
#
# drivers
#
drivers = RunCommand('db.drivers',
- quiet = True,
- read = True,
- flags = 'p')
-
+ quiet=True,
+ read=True,
+ flags='p')
+
self.listOfDrivers = []
for drv in drivers.splitlines():
self.listOfDrivers.append(drv.strip())
-
+
#
# get default values
#
self.defaultConnect = {}
connect = RunCommand('db.connect',
- flags = 'p',
- read = True,
- quiet = True)
-
+ flags='p',
+ read=True,
+ quiet=True)
+
for line in connect.splitlines():
item, value = line.split(':', 1)
self.defaultConnect[item.strip()] = value.strip()
-
- ### really needed?
+
+ # really needed?
# if len(self.defaultConnect['driver']) == 0 or \
# len(self.defaultConnect['database']) == 0:
# GWarning(parent = self.parent,
# message = _("Unknown default DB connection. "
# "Please define DB connection using db.connect module."))
-
+
self.defaultTables = self._getTables(self.defaultConnect['driver'],
self.defaultConnect['database'])
try:
- self.defaultColumns = self._getColumns(self.defaultConnect['driver'],
- self.defaultConnect['database'],
- self.defaultTables[0])
+ self.defaultColumns = self._getColumns(
+ self.defaultConnect['driver'],
+ self.defaultConnect['database'],
+ self.defaultTables[0])
except IndexError:
self.defaultColumns = []
@@ -2735,112 +3035,118 @@
def _createAddPage(self):
"""Add new layer"""
- self.addPanel = wx.Panel(parent = self, id = wx.ID_ANY)
- self.AddPage(page = self.addPanel, text = _("Add layer"))
-
+ self.addPanel = wx.Panel(parent=self, id=wx.ID_ANY)
+ self.AddPage(page=self.addPanel, text=_("Add layer"))
+
try:
maxLayer = max(self.mapDBInfo.layers.keys())
except ValueError:
maxLayer = 0
# layer description
-
- layerBox = wx.StaticBox (parent = self.addPanel, id = wx.ID_ANY,
- label = " %s " % (_("Layer description")))
+
+ layerBox = wx.StaticBox(parent=self.addPanel, id=wx.ID_ANY,
+ label=" %s " % (_("Layer description")))
layerSizer = wx.StaticBoxSizer(layerBox, wx.VERTICAL)
-
+
#
# list of layer widgets (label, value)
#
self.addLayerWidgets = {'layer':
- (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Layer")),
- wx.SpinCtrl(parent = self.addPanel, id = wx.ID_ANY, size = (65, -1),
- initial = maxLayer+1,
- min = 1, max = 1e6)),
+ (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Layer")),
+ wx.SpinCtrl(parent=self.addPanel, id=wx.ID_ANY, size=(65, -1),
+ initial=maxLayer + 1,
+ min=1, max=1e6)),
'driver':
- (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Driver")),
- wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
- choices = self.listOfDrivers)),
+ (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Driver")),
+ wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+ choices=self.listOfDrivers)),
'database':
- (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Database")),
- wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
- value = '',
- style = wx.TE_PROCESS_ENTER)),
+ (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Database")),
+ wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+ value='',
+ style=wx.TE_PROCESS_ENTER)),
'table':
- (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Table")),
- wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
- choices = self.defaultTables)),
+ (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Table")),
+ wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+ choices=self.defaultTables)),
'key':
- (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Key column")),
- wx.Choice(parent = self.addPanel, id = wx.ID_ANY, size = (200, -1),
- choices = self.defaultColumns)),
+ (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Key column")),
+ wx.Choice(parent=self.addPanel, id=wx.ID_ANY, size=(200, -1),
+ choices=self.defaultColumns)),
'addCat':
- (wx.CheckBox(parent = self.addPanel, id = wx.ID_ANY,
- label = _("Insert record for each category into table")),
+ (wx.CheckBox(parent=self.addPanel, id=wx.ID_ANY,
+ label=_("Insert record for each category into table")),
None),
}
-
+
# set default values for widgets
- self.addLayerWidgets['driver'][1].SetStringSelection(self.defaultConnect['driver'])
- self.addLayerWidgets['database'][1].SetValue(self.defaultConnect['database'])
+ self.addLayerWidgets['driver'][1].SetStringSelection(
+ self.defaultConnect['driver'])
+ self.addLayerWidgets['database'][1].SetValue(
+ self.defaultConnect['database'])
self.addLayerWidgets['table'][1].SetSelection(0)
self.addLayerWidgets['key'][1].SetSelection(0)
self.addLayerWidgets['addCat'][0].SetValue(True)
# events
- self.addLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
- self.addLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
- self.addLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
-
+ self.addLayerWidgets['driver'][1].Bind(
+ wx.EVT_CHOICE, self.OnDriverChanged)
+ self.addLayerWidgets['database'][1].Bind(
+ wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
+ self.addLayerWidgets['table'][1].Bind(
+ wx.EVT_CHOICE, self.OnTableChanged)
+
# tooltips
- self.addLayerWidgets['addCat'][0].SetToolTipString(_("You need to add categories "
- "by v.category module."))
+ self.addLayerWidgets['addCat'][0].SetToolTipString(
+ _("You need to add categories " "by v.category module."))
# table description
- tableBox = wx.StaticBox (parent = self.addPanel, id = wx.ID_ANY,
- label = " %s " % (_("Table description")))
+ tableBox = wx.StaticBox(parent=self.addPanel, id=wx.ID_ANY,
+ label=" %s " % (_("Table description")))
tableSizer = wx.StaticBoxSizer(tableBox, wx.VERTICAL)
#
# list of table widgets
#
- keyCol = UserSettings.Get(group = 'atm', key = 'keycolumn', subkey = 'value')
- self.tableWidgets = {'table': (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Table name")),
- wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
- value = '',
- style = wx.TE_PROCESS_ENTER)),
- 'key': (wx.StaticText(parent = self.addPanel, id = wx.ID_ANY,
- label = '%s:' % _("Key column")),
- wx.TextCtrl(parent = self.addPanel, id = wx.ID_ANY,
- value = keyCol,
- style = wx.TE_PROCESS_ENTER))}
+ keyCol = UserSettings.Get(group='atm', key='keycolumn', subkey='value')
+ self.tableWidgets = {'table': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Table name")),
+ wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+ value='',
+ style=wx.TE_PROCESS_ENTER)),
+ 'key': (wx.StaticText(parent=self.addPanel, id=wx.ID_ANY,
+ label='%s:' % _("Key column")),
+ wx.TextCtrl(parent=self.addPanel, id=wx.ID_ANY,
+ value=keyCol,
+ style=wx.TE_PROCESS_ENTER))}
# events
- self.tableWidgets['table'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
+ self.tableWidgets['table'][1].Bind(
+ wx.EVT_TEXT_ENTER, self.OnCreateTable)
self.tableWidgets['key'][1].Bind(wx.EVT_TEXT_ENTER, self.OnCreateTable)
-
- btnTable = wx.Button(self.addPanel, wx.ID_ANY, _("&Create table"),
- size = (125,-1))
+
+ btnTable = wx.Button(self.addPanel, wx.ID_ANY, _("&Create table"),
+ size=(125, -1))
btnTable.Bind(wx.EVT_BUTTON, self.OnCreateTable)
-
- btnLayer = wx.Button(self.addPanel, wx.ID_ANY, _("&Add layer"),
- size = (125,-1))
+
+ btnLayer = wx.Button(self.addPanel, wx.ID_ANY, _("&Add layer"),
+ size=(125, -1))
btnLayer.Bind(wx.EVT_BUTTON, self.OnAddLayer)
-
+
btnDefault = wx.Button(self.addPanel, wx.ID_ANY, _("&Set default"),
- size = (125,-1))
+ size=(125, -1))
btnDefault.Bind(wx.EVT_BUTTON, self.OnSetDefault)
-
+
# do layout
-
+
pageSizer = wx.BoxSizer(wx.HORIZONTAL)
-
+
# data area
- dataSizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+ dataSizer = wx.GridBagSizer(hgap=5, vgap=5)
row = 0
for key in ('layer', 'driver', 'database', 'table', 'key', 'addCat'):
label, value = self.addLayerWidgets[key]
@@ -2848,10 +3154,10 @@
span = (1, 2)
else:
span = (1, 1)
- dataSizer.Add(item = label,
- flag = wx.ALIGN_CENTER_VERTICAL, pos = (row, 0),
- span = span)
-
+ dataSizer.Add(item=label,
+ flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0),
+ span=span)
+
if not value:
row += 1
continue
@@ -2860,69 +3166,69 @@
style = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT
else:
style = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND
-
- dataSizer.Add(item = value,
- flag = style, pos = (row, 1))
-
+
+ dataSizer.Add(item=value,
+ flag=style, pos=(row, 1))
+
row += 1
-
+
dataSizer.AddGrowableCol(1)
- layerSizer.Add(item = dataSizer,
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
-
+ layerSizer.Add(item=dataSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
+
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
- btnSizer.Add(item = btnDefault,
- proportion = 0,
- flag = wx.ALL | wx.ALIGN_LEFT,
- border = 5)
-
- btnSizer.Add(item = (5, 5),
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
-
- btnSizer.Add(item = btnLayer,
- proportion = 0,
- flag = wx.ALL | wx.ALIGN_RIGHT,
- border = 5)
-
- layerSizer.Add(item = btnSizer,
- proportion = 0,
- flag = wx.ALL | wx.EXPAND,
- border = 0)
-
+ btnSizer.Add(item=btnDefault,
+ proportion=0,
+ flag=wx.ALL | wx.ALIGN_LEFT,
+ border=5)
+
+ btnSizer.Add(item=(5, 5),
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
+
+ btnSizer.Add(item=btnLayer,
+ proportion=0,
+ flag=wx.ALL | wx.ALIGN_RIGHT,
+ border=5)
+
+ layerSizer.Add(item=btnSizer,
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=0)
+
# data area
- dataSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+ dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
dataSizer.AddGrowableCol(1)
for key in ['table', 'key']:
label, value = self.tableWidgets[key]
- dataSizer.Add(item = label,
- flag = wx.ALIGN_CENTER_VERTICAL)
- dataSizer.Add(item = value,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
+ dataSizer.Add(item=label,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ dataSizer.Add(item=value,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
- tableSizer.Add(item = dataSizer,
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
+ tableSizer.Add(item=dataSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
- tableSizer.Add(item = btnTable,
- proportion = 0,
- flag = wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT,
- border = 5)
+ tableSizer.Add(item=btnTable,
+ proportion=0,
+ flag=wx.ALL | wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT,
+ border=5)
- pageSizer.Add(item = layerSizer,
- proportion = 3,
- flag = wx.ALL | wx.EXPAND,
- border = 3)
-
- pageSizer.Add(item = tableSizer,
- proportion = 2,
- flag = wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
- border = 3)
+ pageSizer.Add(item=layerSizer,
+ proportion=3,
+ flag=wx.ALL | wx.EXPAND,
+ border=3)
+ pageSizer.Add(item=tableSizer,
+ proportion=2,
+ flag=wx.TOP | wx.BOTTOM | wx.RIGHT | wx.EXPAND,
+ border=3)
+
# SetVirtualSizeHints is deprecated and is
# exactly the same as FitInside() in wxWidgets 2.9 and later
getattr(layerSizer, 'FitInside',
@@ -2931,36 +3237,41 @@
self.addPanel.SetAutoLayout(True)
self.addPanel.SetSizer(pageSizer)
pageSizer.Fit(self.addPanel)
-
+
def _createDeletePage(self):
"""Delete layer"""
- self.deletePanel = wx.Panel(parent = self, id = wx.ID_ANY)
- self.AddPage(page = self.deletePanel, text = _("Remove layer"))
+ self.deletePanel = wx.Panel(parent=self, id=wx.ID_ANY)
+ self.AddPage(page=self.deletePanel, text=_("Remove layer"))
- label = wx.StaticText(parent = self.deletePanel, id = wx.ID_ANY,
- label = '%s:' % _("Layer to remove"))
+ label = wx.StaticText(parent=self.deletePanel, id=wx.ID_ANY,
+ label='%s:' % _("Layer to remove"))
- self.deleteLayer = wx.ComboBox(parent = self.deletePanel, id = wx.ID_ANY, size = (100, -1),
- style = wx.CB_SIMPLE | wx.CB_READONLY,
- choices = map(str, self.mapDBInfo.layers.keys()))
- self.deleteLayer.SetSelection(0)
+ self.deleteLayer = wx.ComboBox(
+ parent=self.deletePanel, id=wx.ID_ANY, size=(100, -1),
+ style=wx.CB_SIMPLE | wx.CB_READONLY,
+ choices=map(str, self.mapDBInfo.layers.keys()))
+ self.deleteLayer.SetSelection(0)
self.deleteLayer.Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
try:
- tableName = self.mapDBInfo.layers[int(self.deleteLayer.GetStringSelection())]['table']
+ tableName = self.mapDBInfo.layers[
+ int(self.deleteLayer.GetStringSelection())]['table']
except ValueError:
tableName = ''
-
- self.deleteTable = wx.CheckBox(parent = self.deletePanel, id = wx.ID_ANY,
- label = _('Drop also linked attribute table (%s)') % \
- tableName)
+ self.deleteTable = wx.CheckBox(
+ parent=self.deletePanel,
+ id=wx.ID_ANY,
+ label=_('Drop also linked attribute table (%s)') %
+ tableName)
+
if tableName == '':
self.deleteLayer.Enable(False)
self.deleteTable.Enable(False)
-
- btnDelete = wx.Button(self.deletePanel, wx.ID_DELETE, _("&Remove layer"),
- size = (125,-1))
+
+ btnDelete = wx.Button(
+ self.deletePanel, wx.ID_DELETE, _("&Remove layer"),
+ size=(125, -1))
btnDelete.Bind(wx.EVT_BUTTON, self.OnDeleteLayer)
#
@@ -2970,89 +3281,90 @@
dataSizer = wx.BoxSizer(wx.VERTICAL)
- flexSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+ flexSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
- flexSizer.Add(item = label,
- flag = wx.ALIGN_CENTER_VERTICAL)
- flexSizer.Add(item = self.deleteLayer,
- flag = wx.ALIGN_CENTER_VERTICAL)
+ flexSizer.Add(item=label,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ flexSizer.Add(item=self.deleteLayer,
+ flag=wx.ALIGN_CENTER_VERTICAL)
- dataSizer.Add(item = flexSizer,
- proportion = 0,
- flag = wx.ALL | wx.EXPAND,
- border = 1)
+ dataSizer.Add(item=flexSizer,
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=1)
- dataSizer.Add(item = self.deleteTable,
- proportion = 0,
- flag = wx.ALL | wx.EXPAND,
- border = 1)
+ dataSizer.Add(item=self.deleteTable,
+ proportion=0,
+ flag=wx.ALL | wx.EXPAND,
+ border=1)
- pageSizer.Add(item = dataSizer,
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
+ pageSizer.Add(item=dataSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
- pageSizer.Add(item = btnDelete,
- proportion = 0,
- flag = wx.ALL | wx.ALIGN_RIGHT,
- border = 5)
+ pageSizer.Add(item=btnDelete,
+ proportion=0,
+ flag=wx.ALL | wx.ALIGN_RIGHT,
+ border=5)
self.deletePanel.SetSizer(pageSizer)
def _createModifyPage(self):
"""Modify layer"""
- self.modifyPanel = wx.Panel(parent = self, id = wx.ID_ANY)
- self.AddPage(page = self.modifyPanel, text = _("Modify layer"))
+ self.modifyPanel = wx.Panel(parent=self, id=wx.ID_ANY)
+ self.AddPage(page=self.modifyPanel, text=_("Modify layer"))
#
# list of layer widgets (label, value)
#
self.modifyLayerWidgets = {'layer':
- (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
- label = '%s:' % _("Layer")),
- wx.ComboBox(parent = self.modifyPanel, id = wx.ID_ANY,
- size = (100, -1),
- style = wx.CB_SIMPLE | wx.CB_READONLY,
- choices = map(str,
- self.mapDBInfo.layers.keys()))),
+ (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+ label='%s:' % _("Layer")),
+ wx.ComboBox(parent=self.modifyPanel, id=wx.ID_ANY,
+ size=(100, -1),
+ style=wx.CB_SIMPLE | wx.CB_READONLY,
+ choices=map(str,
+ self.mapDBInfo.layers.keys()))),
'driver':
- (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
- label = '%s:' % _("Driver")),
- wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
- size = (200, -1),
- choices = self.listOfDrivers)),
+ (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+ label='%s:' % _("Driver")),
+ wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+ size=(200, -1),
+ choices=self.listOfDrivers)),
'database':
- (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
- label = '%s:' % _("Database")),
- wx.TextCtrl(parent = self.modifyPanel, id = wx.ID_ANY,
- value = '', size = (350, -1),
- style = wx.TE_PROCESS_ENTER)),
+ (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+ label='%s:' % _("Database")),
+ wx.TextCtrl(parent=self.modifyPanel, id=wx.ID_ANY,
+ value='', size=(350, -1),
+ style=wx.TE_PROCESS_ENTER)),
'table':
- (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
- label = '%s:' % _("Table")),
- wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
- size = (200, -1),
- choices = self.defaultTables)),
+ (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+ label='%s:' % _("Table")),
+ wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+ size=(200, -1),
+ choices=self.defaultTables)),
'key':
- (wx.StaticText(parent = self.modifyPanel, id = wx.ID_ANY,
- label = '%s:' % _("Key column")),
- wx.Choice(parent = self.modifyPanel, id = wx.ID_ANY,
- size = (200, -1),
- choices = self.defaultColumns))}
-
+ (wx.StaticText(parent=self.modifyPanel, id=wx.ID_ANY,
+ label='%s:' % _("Key column")),
+ wx.Choice(parent=self.modifyPanel, id=wx.ID_ANY,
+ size=(200, -1),
+ choices=self.defaultColumns))}
+
# set default values for widgets
self.modifyLayerWidgets['layer'][1].SetSelection(0)
try:
- layer = int(self.modifyLayerWidgets['layer'][1].GetStringSelection())
+ layer = int(self.modifyLayerWidgets[
+ 'layer'][1].GetStringSelection())
except ValueError:
layer = None
for label in self.modifyLayerWidgets.keys():
self.modifyLayerWidgets[label][1].Enable(False)
if layer:
- driver = self.mapDBInfo.layers[layer]['driver']
+ driver = self.mapDBInfo.layers[layer]['driver']
database = self.mapDBInfo.layers[layer]['database']
- table = self.mapDBInfo.layers[layer]['table']
+ table = self.mapDBInfo.layers[layer]['table']
listOfColumns = self._getColumns(driver, database, table)
self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
@@ -3061,21 +3373,24 @@
self.modifyLayerWidgets['table'][1].SetStringSelection(table)
else:
if self.defaultConnect['schema'] != '':
- table = self.defaultConnect['schema'] + table # try with default schema
+ # try with default schema
+ table = self.defaultConnect['schema'] + table
else:
- table = 'public.' + table # try with 'public' schema
+ table = 'public.' + table # try with 'public' schema
self.modifyLayerWidgets['table'][1].SetStringSelection(table)
self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
self.modifyLayerWidgets['key'][1].SetSelection(0)
# events
- self.modifyLayerWidgets['layer'][1].Bind(wx.EVT_COMBOBOX, self.OnChangeLayer)
+ self.modifyLayerWidgets['layer'][1].Bind(
+ wx.EVT_COMBOBOX, self.OnChangeLayer)
# self.modifyLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged)
# self.modifyLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged)
# self.modifyLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged)
- btnModify = wx.Button(self.modifyPanel, wx.ID_DELETE, _("&Modify layer"),
- size = (125,-1))
+ btnModify = wx.Button(
+ self.modifyPanel, wx.ID_DELETE, _("&Modify layer"),
+ size=(125, -1))
btnModify.Bind(wx.EVT_BUTTON, self.OnModifyLayer)
#
@@ -3084,28 +3399,28 @@
pageSizer = wx.BoxSizer(wx.VERTICAL)
# data area
- dataSizer = wx.FlexGridSizer(cols = 2, hgap = 5, vgap = 5)
+ dataSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
dataSizer.AddGrowableCol(1)
for key in ('layer', 'driver', 'database', 'table', 'key'):
label, value = self.modifyLayerWidgets[key]
- dataSizer.Add(item = label,
- flag = wx.ALIGN_CENTER_VERTICAL)
+ dataSizer.Add(item=label,
+ flag=wx.ALIGN_CENTER_VERTICAL)
if key == 'layer':
- dataSizer.Add(item = value,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
+ dataSizer.Add(item=value,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_LEFT)
else:
- dataSizer.Add(item = value,
- flag = wx.ALIGN_CENTER_VERTICAL)
+ dataSizer.Add(item=value,
+ flag=wx.ALIGN_CENTER_VERTICAL)
- pageSizer.Add(item = dataSizer,
- proportion = 1,
- flag = wx.ALL | wx.EXPAND,
- border = 5)
+ pageSizer.Add(item=dataSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
- pageSizer.Add(item = btnModify,
- proportion = 0,
- flag = wx.ALL | wx.ALIGN_RIGHT,
- border = 5)
+ pageSizer.Add(item=btnModify,
+ proportion=0,
+ flag=wx.ALL | wx.ALIGN_RIGHT,
+ border=5)
self.modifyPanel.SetSizer(pageSizer)
@@ -3114,22 +3429,23 @@
tables = []
ret = RunCommand('db.tables',
- parent = self,
- read = True,
- flags = 'p',
- driver = driver,
- database = database)
-
+ parent=self,
+ read=True,
+ flags='p',
+ driver=driver,
+ database=database)
+
if ret is None:
- GError(parent = self,
- message = _("Unable to get list of tables.\n"
- "Please use db.connect to set database parameters."))
-
+ GError(
+ parent=self, message=_(
+ "Unable to get list of tables.\n"
+ "Please use db.connect to set database parameters."))
+
return tables
-
+
for table in ret.splitlines():
tables.append(table)
-
+
return tables
def _getColumns(self, driver, database, table):
@@ -3137,19 +3453,19 @@
columns = []
ret = RunCommand('db.columns',
- parent = self,
- quiet = True,
- read = True,
- driver = driver,
- database = database,
- table = table)
-
- if ret == None:
+ parent=self,
+ quiet=True,
+ read=True,
+ driver=driver,
+ database=database,
+ table=table)
+
+ if ret is None:
return columns
-
+
for column in ret.splitlines():
columns.append(column)
-
+
return columns
def OnDriverChanged(self, event):
@@ -3158,8 +3474,8 @@
database = self.addLayerWidgets['database'][1].GetValue()
winTable = self.addLayerWidgets['table'][1]
- winKey = self.addLayerWidgets['key'][1]
- tables = self._getTables(driver, database)
+ winKey = self.addLayerWidgets['key'][1]
+ tables = self._getTables(driver, database)
winTable.SetItems(tables)
winTable.SetSelection(0)
@@ -3175,11 +3491,11 @@
def OnTableChanged(self, event):
"""Table name changed, update list of columns"""
- driver = self.addLayerWidgets['driver'][1].GetStringSelection()
+ driver = self.addLayerWidgets['driver'][1].GetStringSelection()
database = self.addLayerWidgets['database'][1].GetValue()
- table = event.GetString()
+ table = event.GetString()
- win = self.addLayerWidgets['key'][1]
+ win = self.addLayerWidgets['key'][1]
cols = self._getColumns(driver, database, table)
win.SetItems(cols)
win.SetSelection(0)
@@ -3188,23 +3504,23 @@
def OnSetDefault(self, event):
"""Set default values"""
- driver = self.addLayerWidgets['driver'][1]
+ driver = self.addLayerWidgets['driver'][1]
database = self.addLayerWidgets['database'][1]
- table = self.addLayerWidgets['table'][1]
- key = self.addLayerWidgets['key'][1]
+ table = self.addLayerWidgets['table'][1]
+ key = self.addLayerWidgets['key'][1]
driver.SetStringSelection(self.defaultConnect['driver'])
database.SetValue(self.defaultConnect['database'])
tables = self._getTables(self.defaultConnect['driver'],
- self.defaultConnect['database'])
+ self.defaultConnect['database'])
table.SetItems(tables)
table.SetSelection(0)
if len(tables) == 0:
key.SetItems([])
else:
cols = self._getColumns(self.defaultConnect['driver'],
- self.defaultConnect['database'],
- tables[0])
+ self.defaultConnect['database'],
+ tables[0])
key.SetItems(cols)
key.SetSelection(0)
@@ -3212,34 +3528,36 @@
def OnCreateTable(self, event):
"""Create new table (name and key column given)"""
- driver = self.addLayerWidgets['driver'][1].GetStringSelection()
+ driver = self.addLayerWidgets['driver'][1].GetStringSelection()
database = self.addLayerWidgets['database'][1].GetValue()
- table = self.tableWidgets['table'][1].GetValue()
- key = self.tableWidgets['key'][1].GetValue()
-
+ table = self.tableWidgets['table'][1].GetValue()
+ key = self.tableWidgets['key'][1].GetValue()
+
if not table or not key:
- GError(parent = self,
- message = _("Unable to create new table. "
- "Table name or key column name is missing."))
+ GError(parent=self,
+ message=_("Unable to create new table. "
+ "Table name or key column name is missing."))
return
if table in self.addLayerWidgets['table'][1].GetItems():
- GError(parent = self,
- message = _("Unable to create new table. "
- "Table <%s> already exists in the database.") % table)
+ GError(
+ parent=self, message=_(
+ "Unable to create new table. "
+ "Table <%s> already exists in the database.") %
+ table)
return
-
+
# create table
sql = 'CREATE TABLE %s (%s INTEGER)' % (table, key)
RunCommand('db.execute',
- quiet = True,
- parent = self,
- stdin = sql,
- input = '-',
- driver = driver,
- database = database)
-
+ quiet=True,
+ parent=self,
+ stdin=sql,
+ input='-',
+ driver=driver,
+ database=database)
+
# update list of tables
tableList = self.addLayerWidgets['table'][1]
tableList.SetItems(self._getTables(driver, database))
@@ -3249,54 +3567,56 @@
keyList = self.addLayerWidgets['key'][1]
keyList.SetItems(self._getColumns(driver, database, table))
keyList.SetStringSelection(key)
-
+
event.Skip()
def OnAddLayer(self, event):
"""Add new layer to vector map"""
- layer = int(self.addLayerWidgets['layer'][1].GetValue())
+ layer = int(self.addLayerWidgets['layer'][1].GetValue())
layerWin = self.addLayerWidgets['layer'][1]
- driver = self.addLayerWidgets['driver'][1].GetStringSelection()
+ driver = self.addLayerWidgets['driver'][1].GetStringSelection()
database = self.addLayerWidgets['database'][1].GetValue()
- table = self.addLayerWidgets['table'][1].GetStringSelection()
- key = self.addLayerWidgets['key'][1].GetStringSelection()
-
+ table = self.addLayerWidgets['table'][1].GetStringSelection()
+ key = self.addLayerWidgets['key'][1].GetStringSelection()
+
if layer in self.mapDBInfo.layers.keys():
- GError(parent = self,
- message = _("Unable to add new layer to vector map <%(vector)s>. "
- "Layer %(layer)d already exists.") % \
- {'vector' : self.mapDBInfo.map, 'layer' : layer})
+ GError(
+ parent=self,
+ message=_(
+ "Unable to add new layer to vector map <%(vector)s>. "
+ "Layer %(layer)d already exists.") %
+ {'vector': self.mapDBInfo.map, 'layer': layer})
return
# add new layer
ret = RunCommand('v.db.connect',
- parent = self,
- quiet = True,
- map = self.mapDBInfo.map,
- driver = driver,
- database = database,
- table = table,
- key = key,
- layer = layer)
-
+ parent=self,
+ quiet=True,
+ map=self.mapDBInfo.map,
+ driver=driver,
+ database=database,
+ table=table,
+ key=key,
+ layer=layer)
+
# insert records into table if required
if self.addLayerWidgets['addCat'][0].IsChecked():
RunCommand('v.to.db',
- parent = self,
- quiet = True,
- map = self.mapDBInfo.map,
- layer = layer,
- qlayer = layer,
- option = 'cat',
- columns = key)
+ parent=self,
+ quiet=True,
+ map=self.mapDBInfo.map,
+ layer=layer,
+ qlayer=layer,
+ option='cat',
+ columns=key)
if ret == 0:
# update dialog (only for new layer)
- self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer)
+ self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
# update db info
self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
# increase layer number
- layerWin.SetValue(layer+1)
+ layerWin.SetValue(layer + 1)
if len(self.mapDBInfo.layers.keys()) == 1:
# first layer add --- enable previously disabled widgets
@@ -3304,7 +3624,7 @@
self.deleteTable.Enable()
for label in self.modifyLayerWidgets.keys():
self.modifyLayerWidgets[label][1].Enable()
-
+
def OnDeleteLayer(self, event):
"""Delete layer"""
try:
@@ -3313,17 +3633,17 @@
return
RunCommand('v.db.connect',
- parent = self,
- flags = 'd',
- map = self.mapDBInfo.map,
- layer = layer)
+ parent=self,
+ flags='d',
+ map=self.mapDBInfo.map,
+ layer=layer)
# drop also table linked to layer which is deleted
if self.deleteTable.IsChecked():
- driver = self.addLayerWidgets['driver'][1].GetStringSelection()
+ driver = self.addLayerWidgets['driver'][1].GetStringSelection()
database = self.addLayerWidgets['database'][1].GetValue()
- table = self.mapDBInfo.layers[layer]['table']
- sql = 'DROP TABLE %s' % (table)
+ table = self.mapDBInfo.layers[layer]['table']
+ sql = 'DROP TABLE %s' % (table)
RunCommand('db.execute',
input='-',
@@ -3332,14 +3652,14 @@
quiet=True,
driver=driver,
database=database)
-
+
# update list of tables
tableList = self.addLayerWidgets['table'][1]
tableList.SetItems(self._getTables(driver, database))
tableList.SetStringSelection(table)
-
+
# update dialog
- self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer)
+ self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
# update db info
self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
@@ -3349,7 +3669,7 @@
self.deleteTable.Enable(False)
for label in self.modifyLayerWidgets.keys():
self.modifyLayerWidgets[label][1].Enable(False)
-
+
event.Skip()
def OnChangeLayer(self, event):
@@ -3363,9 +3683,9 @@
return
if self.GetCurrentPage() == self.modifyPanel:
- driver = self.mapDBInfo.layers[layer]['driver']
+ driver = self.mapDBInfo.layers[layer]['driver']
database = self.mapDBInfo.layers[layer]['database']
- table = self.mapDBInfo.layers[layer]['table']
+ table = self.mapDBInfo.layers[layer]['table']
listOfColumns = self._getColumns(driver, database, table)
self.modifyLayerWidgets['driver'][1].SetStringSelection(driver)
self.modifyLayerWidgets['database'][1].SetValue(database)
@@ -3373,8 +3693,9 @@
self.modifyLayerWidgets['key'][1].SetItems(listOfColumns)
self.modifyLayerWidgets['key'][1].SetSelection(0)
else:
- self.deleteTable.SetLabel(_('Drop also linked attribute table (%s)') % \
- self.mapDBInfo.layers[layer]['table'])
+ self.deleteTable.SetLabel(
+ _('Drop also linked attribute table (%s)') %
+ self.mapDBInfo.layers[layer]['table'])
if event:
event.Skip()
@@ -3397,57 +3718,69 @@
if modify:
# delete layer
RunCommand('v.db.connect',
- parent = self,
- quiet = True,
- flags = 'd',
- map = self.mapDBInfo.map,
- layer = layer)
+ parent=self,
+ quiet=True,
+ flags='d',
+ map=self.mapDBInfo.map,
+ layer=layer)
# add modified layer
- RunCommand('v.db.connect',
- quiet = True,
- map = self.mapDBInfo.map,
- driver = self.modifyLayerWidgets['driver'][1].GetStringSelection(),
- database = self.modifyLayerWidgets['database'][1].GetValue(),
- table = self.modifyLayerWidgets['table'][1].GetStringSelection(),
- key = self.modifyLayerWidgets['key'][1].GetStringSelection(),
- layer = int(layer))
-
+ RunCommand(
+ 'v.db.connect',
+ quiet=True,
+ map=self.mapDBInfo.map,
+ driver=self.modifyLayerWidgets['driver'][1].GetStringSelection(),
+ database=self.modifyLayerWidgets['database'][1].GetValue(),
+ table=self.modifyLayerWidgets['table'][1].GetStringSelection(),
+ key=self.modifyLayerWidgets['key'][1].GetStringSelection(),
+ layer=int(layer))
+
# update dialog (only for new layer)
- self.parentDialog.parentDbMgrBase.UpdateDialog(layer = layer)
+ self.parentDialog.parentDbMgrBase.UpdateDialog(layer=layer)
# update db info
self.mapDBInfo = self.parentDialog.dbMgrData['mapDBInfo']
event.Skip()
+
class FieldStatistics(wx.Frame):
+
def __init__(self, parent, id=wx.ID_ANY,
- style = wx.DEFAULT_FRAME_STYLE, **kwargs):
+ style=wx.DEFAULT_FRAME_STYLE, **kwargs):
"""Dialog to display and save statistics of field stats
"""
self.parent = parent
- wx.Frame.__init__(self, parent, id, style = style, **kwargs)
-
+ wx.Frame.__init__(self, parent, id, style=style, **kwargs)
+
self.SetTitle(_("Field statistics"))
- self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
+ self.SetIcon(
+ wx.Icon(
+ os.path.join(
+ globalvar.ICONDIR,
+ 'grass_sql.ico'),
+ wx.BITMAP_TYPE_ICO))
- self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-
- self.sp = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY, size=(250, 150),
- style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER, name="Statistics" )
- self.text = wx.TextCtrl(parent=self.sp, id=wx.ID_ANY, style=wx.TE_MULTILINE|wx.TE_READONLY)
+ self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
+ self.sp = scrolled.ScrolledPanel(parent=self.panel, id=wx.ID_ANY, size=(
+ 250, 150), style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER, name="Statistics")
+ self.text = wx.TextCtrl(
+ parent=self.sp,
+ id=wx.ID_ANY,
+ style=wx.TE_MULTILINE | wx.TE_READONLY)
self.text.SetBackgroundColour("white")
-
+
# buttons
- self.btnClipboard = wx.Button(parent=self.panel, id = wx.ID_COPY)
- self.btnClipboard.SetToolTipString(_("Copy statistics the clipboard (Ctrl+C)"))
+ self.btnClipboard = wx.Button(parent=self.panel, id=wx.ID_COPY)
+ self.btnClipboard.SetToolTipString(
+ _("Copy statistics the clipboard (Ctrl+C)"))
self.btnCancel = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
self.btnCancel.SetDefault()
# bindings
self.btnCancel.Bind(wx.EVT_BUTTON, self.OnClose)
self.btnClipboard.Bind(wx.EVT_BUTTON, self.OnCopy)
-
+
self._layout()
def _layout(self):
@@ -3455,27 +3788,31 @@
txtSizer = wx.BoxSizer(wx.VERTICAL)
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
- txtSizer.Add(item = self.text, proportion = 1,
- flag = wx.EXPAND|wx.ALIGN_CENTER_VERTICAL|wx.ALL, border = 5)
-
+ txtSizer.Add(item=self.text, proportion=1, flag=wx.EXPAND |
+ wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+
self.sp.SetSizer(txtSizer)
self.sp.SetAutoLayout(True)
- self.sp.SetupScrolling()
+ self.sp.SetupScrolling()
- sizer.Add(item = self.sp, proportion = 1, flag = wx.GROW |
- wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 3)
+ sizer.Add(item=self.sp, proportion=1, flag=wx.GROW |
+ wx.LEFT | wx.RIGHT | wx.BOTTOM, border=3)
- line = wx.StaticLine(parent = self.panel, id = wx.ID_ANY,
- size = (20, -1), style = wx.LI_HORIZONTAL)
- sizer.Add(item = line, proportion = 0,
- flag = wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.LEFT|wx.RIGHT, border = 3)
+ line = wx.StaticLine(parent=self.panel, id=wx.ID_ANY,
+ size=(20, -1), style=wx.LI_HORIZONTAL)
+ sizer.Add(item=line, proportion=0, flag=wx.GROW |
+ wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT, border=3)
# buttons
- btnSizer.Add(item = self.btnClipboard, proportion = 0,
- flag = wx.ALIGN_LEFT | wx.ALL, border = 5)
- btnSizer.Add(item = self.btnCancel, proportion = 0,
- flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
- sizer.Add(item = btnSizer, proportion = 0, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+ btnSizer.Add(item=self.btnClipboard, proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALL, border=5)
+ btnSizer.Add(item=self.btnCancel, proportion=0,
+ flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+ sizer.Add(
+ item=btnSizer,
+ proportion=0,
+ flag=wx.ALIGN_RIGHT | wx.ALL,
+ border=5)
self.panel.SetSizer(sizer)
sizer.Fit(self.panel)
@@ -3486,7 +3823,7 @@
stats = self.text.GetValue()
rdata = wx.TextDataObject()
rdata.SetText(stats)
-
+
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(rdata)
wx.TheClipboard.Close()
@@ -3498,7 +3835,7 @@
def Update(self, driver, database, table, column):
"""!Update statistics for given column
-
+
:param: column column name
"""
if driver == 'dbf':
@@ -3506,57 +3843,64 @@
message=_("Statistics is not support for DBF tables."))
self.Close()
return
-
+
fd, sqlFilePath = tempfile.mkstemp(text=True)
sqlFile = open(sqlFilePath, 'w')
stats = ['count', 'min', 'max', 'avg', 'sum', 'null']
for fn in stats:
if fn == 'null':
- sqlFile.write('select count(*) from %s where %s is null;%s' % (table, column, os.linesep))
+ sqlFile.write(
+ 'select count(*) from %s where %s is null;%s' %
+ (table, column, os.linesep))
else:
- sqlFile.write('select %s(%s) from %s;%s' % (fn, column, table, os.linesep))
+ sqlFile.write(
+ 'select %s(%s) from %s;%s' %
+ (fn, column, table, os.linesep))
sqlFile.close()
-
+
dataStr = RunCommand('db.select',
- parent = self.parent,
- read = True,
+ parent=self.parent,
+ read=True,
flags='c',
- input = sqlFilePath,
- driver = driver,
- database = database)
+ input=sqlFilePath,
+ driver=driver,
+ database=database)
if not dataStr:
- GError(parent = self.parent,
- message = _("Unable to calculte statistics."))
+ GError(parent=self.parent,
+ message=_("Unable to calculte statistics."))
self.Close()
return
-
+
dataLines = dataStr.splitlines()
if len(dataLines) != len(stats):
- GError(parent = self.parent,
- message = _("Unable to calculte statistics. "
- "Invalid number of lines %d (should be %d).") % (len(dataLines), len(stats)))
+ GError(
+ parent=self.parent, message=_(
+ "Unable to calculte statistics. "
+ "Invalid number of lines %d (should be %d).") %
+ (len(dataLines), len(stats)))
self.Close()
return
-
+
# calculate stddev
avg = float(dataLines[stats.index('avg')])
count = float(dataLines[stats.index('count')])
- sql = "select (%(column)s - %(avg)f)*(%(column)s - %(avg)f) from %(table)s" % { 'column' : column, 'avg' : avg, 'table' : table }
+ sql = "select (%(column)s - %(avg)f)*(%(column)s - %(avg)f) from %(table)s" % {
+ 'column': column, 'avg': avg, 'table': table}
dataVar = RunCommand('db.select',
- parent = self.parent,
- read = True,
+ parent=self.parent,
+ read=True,
flags='c',
- sql = sql,
- driver = driver,
- database = database)
+ sql=sql,
+ driver=driver,
+ database=database)
if not dataVar:
- GWarning(parent = self.parent,
- message = _("Unable to calculte standard deviation."))
+ GWarning(parent=self.parent,
+ message=_("Unable to calculte standard deviation."))
varSum = 0
for var in dataVar.splitlines():
varSum += float(var)
- stddev = math.sqrt(varSum/count)
-
+ stddev = math.sqrt(varSum / count)
+
self.SetTitle(_("Field statistics <%s>") % column)
self.text.Clear()
for idx in range(len(stats)):
Modified: grass/trunk/gui/wxpython/dbmgr/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/dialogs.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/dialogs.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -25,24 +25,26 @@
import wx
import wx.lib.scrolledpanel as scrolled
-from core.gcmd import RunCommand, GError
-from core.debug import Debug
-from core.settings import UserSettings
-from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue
+from core.gcmd import RunCommand, GError
+from core.debug import Debug
+from core.settings import UserSettings
+from dbmgr.vinfo import VectorDBInfo, GetUnicodeValue
from gui_core.widgets import IntegerValidator, FloatValidator
+
class DisplayAttributesDialog(wx.Dialog):
+
def __init__(self, parent, map,
- query = None, cats = None, line = None,
- style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
- pos = wx.DefaultPosition,
- action = "add", ignoreError = False):
+ query=None, cats=None, line=None,
+ style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER,
+ pos=wx.DefaultPosition,
+ action="add", ignoreError=False):
"""Standard dialog used to add/update/display attributes linked
to the vector map.
-
+
Attribute data can be selected based on layer and category number
or coordinates.
-
+
:param parent:
:param map: vector map
:param query: query coordinates and distance (used for v.edit)
@@ -53,63 +55,67 @@
:param action: (add, update, display)
:param ignoreError: True to ignore errors
"""
- self.parent = parent # mapdisplay.BufferedWindow
- self.map = map
+ self.parent = parent # mapdisplay.BufferedWindow
+ self.map = map
self.action = action
# ids/cats of selected features
# fid : {layer : cats}
self.cats = {}
- self.fid = -1 # feature id
-
+ self.fid = -1 # feature id
+
# get layer/table/column information
self.mapDBInfo = VectorDBInfo(self.map)
-
- layers = self.mapDBInfo.layers.keys() # get available layers
+ layers = self.mapDBInfo.layers.keys() # get available layers
+
# check if db connection / layer exists
if len(layers) <= 0:
if not ignoreError:
- dlg = wx.MessageDialog(parent = self.parent,
- message = _("No attribute table found.\n\n"
- "Do you want to create a new attribute table "
- "and defined a link to vector map <%s>?") % self.map,
- caption = _("Create table?"),
- style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+ dlg = wx.MessageDialog(
+ parent=self.parent,
+ message=_(
+ "No attribute table found.\n\n"
+ "Do you want to create a new attribute table "
+ "and defined a link to vector map <%s>?") %
+ self.map,
+ caption=_("Create table?"),
+ style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
lmgr = self.parent.lmgr
- lmgr.OnShowAttributeTable(event = None, selection = 'layers')
-
+ lmgr.OnShowAttributeTable(event=None, selection='layers')
+
dlg.Destroy()
-
+
self.mapDBInfo = None
-
- wx.Dialog.__init__(self, parent = self.parent, id = wx.ID_ANY,
- title = "", style = style, pos = pos)
+ wx.Dialog.__init__(self, parent=self.parent, id=wx.ID_ANY,
+ title="", style=style, pos=pos)
+
# dialog body
mainSizer = wx.BoxSizer(wx.VERTICAL)
# notebook
- self.notebook = wx.Notebook(parent = self, id = wx.ID_ANY, style = wx.BK_DEFAULT)
+ self.notebook = wx.Notebook(
+ parent=self, id=wx.ID_ANY, style=wx.BK_DEFAULT)
- self.closeDialog = wx.CheckBox(parent = self, id = wx.ID_ANY,
- label = _("Close dialog on submit"))
+ self.closeDialog = wx.CheckBox(parent=self, id=wx.ID_ANY,
+ label=_("Close dialog on submit"))
self.closeDialog.SetValue(True)
if self.action == 'display':
self.closeDialog.Enable(False)
-
+
# feature id (text/choice for duplicates)
- self.fidMulti = wx.Choice(parent = self, id = wx.ID_ANY,
- size = (150, -1))
+ self.fidMulti = wx.Choice(parent=self, id=wx.ID_ANY,
+ size=(150, -1))
self.fidMulti.Bind(wx.EVT_CHOICE, self.OnFeature)
- self.fidText = wx.StaticText(parent = self, id = wx.ID_ANY)
+ self.fidText = wx.StaticText(parent=self, id=wx.ID_ANY)
- self.noFoundMsg = wx.StaticText(parent = self, id = wx.ID_ANY,
- label = _("No attributes found"))
-
- self.UpdateDialog(query = query, cats = cats)
+ self.noFoundMsg = wx.StaticText(parent=self, id=wx.ID_ANY,
+ label=_("No attributes found"))
+ self.UpdateDialog(query=query, cats=cats)
+
# set title
if self.action == "update":
self.SetTitle(_("Update attributes"))
@@ -120,11 +126,11 @@
# buttons
btnCancel = wx.Button(self, wx.ID_CANCEL)
- btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload"))
+ btnReset = wx.Button(self, wx.ID_UNDO, _("&Reload"))
btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
if self.action == 'display':
btnSubmit.Enable(False)
-
+
btnSizer = wx.StdDialogButtonSizer()
btnSizer.AddButton(btnCancel)
btnSizer.AddButton(btnReset)
@@ -133,25 +139,28 @@
btnSizer.AddButton(btnSubmit)
btnSizer.Realize()
- mainSizer.Add(item = self.noFoundMsg, proportion = 0,
- flag = wx.EXPAND | wx.ALL, border = 5)
- mainSizer.Add(item = self.notebook, proportion = 1,
- flag = wx.EXPAND | wx.ALL, border = 5)
+ mainSizer.Add(item=self.noFoundMsg, proportion=0,
+ flag=wx.EXPAND | wx.ALL, border=5)
+ mainSizer.Add(item=self.notebook, proportion=1,
+ flag=wx.EXPAND | wx.ALL, border=5)
fidSizer = wx.BoxSizer(wx.HORIZONTAL)
- fidSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
- label = _("Feature id:")),
- proportion = 0, border = 5,
- flag = wx.ALIGN_CENTER_VERTICAL)
- fidSizer.Add(item = self.fidMulti, proportion = 0,
- flag = wx.EXPAND | wx.ALL, border = 5)
- fidSizer.Add(item = self.fidText, proportion = 0,
- flag = wx.EXPAND | wx.ALL, border = 5)
- mainSizer.Add(item = fidSizer, proportion = 0,
- flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
- mainSizer.Add(item = self.closeDialog, proportion = 0, flag = wx.EXPAND | wx.LEFT | wx.RIGHT,
- border = 5)
- mainSizer.Add(item = btnSizer, proportion = 0,
- flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border = 5)
+ fidSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+ label=_("Feature id:")),
+ proportion=0, border=5,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ fidSizer.Add(item=self.fidMulti, proportion=0,
+ flag=wx.EXPAND | wx.ALL, border=5)
+ fidSizer.Add(item=self.fidText, proportion=0,
+ flag=wx.EXPAND | wx.ALL, border=5)
+ mainSizer.Add(item=fidSizer, proportion=0,
+ flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+ mainSizer.Add(
+ item=self.closeDialog,
+ proportion=0,
+ flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
+ border=5)
+ mainSizer.Add(item=btnSizer, proportion=0,
+ flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
# bindigs
btnReset.Bind(wx.EVT_BUTTON, self.OnReset)
@@ -169,11 +178,11 @@
self.SetMinSize((w, 200))
else:
self.SetMinSize((w, h))
-
+
if self.notebook.GetPageCount() == 0:
Debug.msg(2, "DisplayAttributesDialog(): Nothing found!")
### self.mapDBInfo = None
-
+
def OnSQLStatement(self, event):
"""Update SQL statement"""
pass
@@ -185,36 +194,36 @@
:return: False attributes not found
"""
return bool(self.mapDBInfo and self.notebook.GetPageCount() > 0)
-
- def GetSQLString(self, updateValues = False):
+
+ def GetSQLString(self, updateValues=False):
"""Create SQL statement string based on self.sqlStatement
Show error message when invalid values are entered.
-
+
If updateValues is True, update dataFrame according to values
in textfields.
"""
sqlCommands = []
# find updated values for each layer/category
- for layer in self.mapDBInfo.layers.keys(): # for each layer
+ for layer in self.mapDBInfo.layers.keys(): # for each layer
table = self.mapDBInfo.GetTable(layer)
key = self.mapDBInfo.GetKeyColumn(layer)
columns = self.mapDBInfo.GetTableDesc(table)
- for idx in range(len(columns[key]['values'])): # for each category
+ for idx in range(len(columns[key]['values'])): # for each category
updatedColumns = []
updatedValues = []
for name in columns.keys():
if name == key:
cat = columns[name]['values'][idx]
continue
- ctype = columns[name]['ctype']
+ ctype = columns[name]['ctype']
value = columns[name]['values'][idx]
- id = columns[name]['ids'][idx]
+ id = columns[name]['ids'][idx]
try:
newvalue = self.FindWindowById(id).GetValue()
except:
newvalue = self.FindWindowById(id).GetLabel()
-
+
if newvalue:
try:
if ctype == int:
@@ -222,18 +231,19 @@
elif ctype == float:
newvalue = float(newvalue)
except ValueError:
- GError(parent = self,
- message = _("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % \
- {'col' : name,
- 'value' : str(newvalue),
- 'type' : columns[name]['type'].lower()},
- showTraceback = False)
+ GError(
+ parent=self,
+ message=_("Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s.") % {
+ 'col': name,
+ 'value': str(newvalue),
+ 'type': columns[name]['type'].lower()},
+ showTraceback=False)
sqlCommands.append(None)
continue
else:
if self.action == 'add':
continue
-
+
if newvalue != value:
updatedColumns.append(name)
if not newvalue:
@@ -260,13 +270,13 @@
else:
sqlString += name + "=" + updatedValues[idx] + ","
- sqlString = sqlString[:-1] # remove last comma
+ sqlString = sqlString[:-1] # remove last comma
if self.action == "add":
sqlString += ") VALUES (%s," % cat
for value in updatedValues:
sqlString += value + ","
- sqlString = sqlString[:-1] # remove last comma
+ sqlString = sqlString[:-1] # remove last comma
sqlString += ")"
else:
sqlString += " WHERE %s=%s" % (key, cat)
@@ -274,11 +284,13 @@
# for each category
# for each layer END
- Debug.msg(3, "DisplayAttributesDialog.GetSQLString(): %s" % sqlCommands)
+ Debug.msg(
+ 3, "DisplayAttributesDialog.GetSQLString(): %s" %
+ sqlCommands)
return sqlCommands
- def OnReset(self, event = None):
+ def OnReset(self, event=None):
"""Reset form"""
for layer in self.mapDBInfo.layers.keys():
table = self.mapDBInfo.layers[layer]["table"]
@@ -286,7 +298,7 @@
columns = self.mapDBInfo.tables[table]
for idx in range(len(columns[key]['values'])):
for name in columns.keys():
- type = columns[name]['type']
+ type = columns[name]['type']
value = columns[name]['values'][idx]
if value is None:
value = ''
@@ -294,7 +306,7 @@
id = columns[name]['ids'][idx]
except IndexError:
id = wx.NOT_FOUND
-
+
if name != key and id != wx.NOT_FOUND:
self.FindWindowById(id).SetValue(str(value))
@@ -306,10 +318,10 @@
if hasattr(self, "digit"):
self.parent.digit.GetDisplay().SetSelected([])
if frame.IsAutoRendered():
- self.parent.UpdateMap(render = False)
+ self.parent.UpdateMap(render=False)
elif frame.IsAutoRendered():
frame.RemoveQueryLayer()
- self.parent.UpdateMap(render = True)
+ self.parent.UpdateMap(render=True)
if self.IsModal():
self.EndModal(wx.ID_OK)
else:
@@ -319,11 +331,11 @@
"""Submit records"""
layer = 1
close = True
- enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+ enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
if not enc and 'GRASS_DB_ENCODING' in os.environ:
enc = os.environ['GRASS_DB_ENCODING']
-
- for sql in self.GetSQLString(updateValues = True):
+
+ for sql in self.GetSQLString(updateValues=True):
if not sql:
close = False
continue
@@ -331,26 +343,26 @@
sql = sql.encode(enc)
else:
sql = sql.encode('utf-8')
-
+
driver, database = self.mapDBInfo.GetDbSettings(layer)
Debug.msg(1, "SQL: %s" % sql)
RunCommand('db.execute',
- parent = self,
- quiet = True,
- input = '-',
- stdin = sql,
- driver = driver,
- database = database)
-
+ parent=self,
+ quiet=True,
+ input='-',
+ stdin=sql,
+ driver=driver,
+ database=database)
+
layer += 1
-
+
if close and self.closeDialog.IsChecked():
self.OnClose(event)
def OnFeature(self, event):
self.fid = int(event.GetString())
- self.UpdateDialog(cats = self.cats, fid = self.fid)
-
+ self.UpdateDialog(cats=self.cats, fid=self.fid)
+
def GetCats(self):
"""Get id of selected vector object or 'None' if nothing selected
@@ -358,23 +370,23 @@
"""
if self.fid < 0:
return None
-
+
return self.cats[self.fid]
def GetFid(self):
"""Get selected feature id"""
return self.fid
-
- def UpdateDialog(self, map = None, query = None, cats = None, fid = -1,
- action = None):
+
+ def UpdateDialog(self, map=None, query=None, cats=None, fid=-1,
+ action=None):
"""Update dialog
-
+
:param map: name of vector map
:param query:
:param cats:
:param fid: feature id
:param action: add, update, display or None
-
+
:return: True if updated
:return: False
"""
@@ -386,21 +398,21 @@
enabled = True
self.closeDialog.Enable(enabled)
self.FindWindowById(wx.ID_OK).Enable(enabled)
-
+
if map:
self.map = map
# get layer/table/column information
self.mapDBInfo = VectorDBInfo(self.map)
-
+
if not self.mapDBInfo:
return False
-
+
self.mapDBInfo.Reset()
-
- layers = self.mapDBInfo.layers.keys() # get available layers
-
+
+ layers = self.mapDBInfo.layers.keys() # get available layers
+
# id of selected line
- if query: # select by position
+ if query: # select by position
data = self.mapDBInfo.SelectByPoint(query[0],
query[1])
self.cats = {}
@@ -411,7 +423,7 @@
if data['Id'][idx] is not None:
tfid = int(data['Id'][idx])
else:
- tfid = 0 # Area / Volume
+ tfid = 0 # Area / Volume
if not tfid in self.cats:
self.cats[tfid] = {}
if not layer in self.cats[tfid]:
@@ -421,14 +433,14 @@
idx += 1
else:
self.cats = cats
-
+
if fid > 0:
self.fid = fid
elif len(self.cats.keys()) > 0:
self.fid = self.cats.keys()[0]
else:
self.fid = -1
-
+
if len(self.cats.keys()) == 1:
self.fidMulti.Show(False)
self.fidText.Show(True)
@@ -444,24 +456,23 @@
choices.append(str(tfid))
self.fidMulti.SetItems(choices)
self.fidMulti.SetStringSelection(str(self.fid))
-
+
# reset notebook
self.notebook.DeleteAllPages()
-
- for layer in layers: # for each layer
- if not query: # select by layer/cat
+
+ for layer in layers: # for each layer
+ if not query: # select by layer/cat
if self.fid > 0 and layer in self.cats[self.fid]:
for cat in self.cats[self.fid][layer]:
- nselected = self.mapDBInfo.SelectFromTable(layer,
- where = "%s=%d" % \
- (self.mapDBInfo.layers[layer]['key'],
- cat))
+ nselected = self.mapDBInfo.SelectFromTable(
+ layer, where="%s=%d" %
+ (self.mapDBInfo.layers[layer]['key'], cat))
else:
nselected = 0
-
+
# if nselected <= 0 and self.action != "add":
# continue # nothing selected ...
-
+
if self.action == "add":
if nselected <= 0:
if layer in self.cats[self.fid]:
@@ -471,47 +482,51 @@
for name in columns.keys():
if name == key:
for cat in self.cats[self.fid][layer]:
- self.mapDBInfo.tables[table][name]['values'].append(cat)
+ self.mapDBInfo.tables[table][
+ name]['values'].append(cat)
else:
- self.mapDBInfo.tables[table][name]['values'].append(None)
- else: # change status 'add' -> 'update'
+ self.mapDBInfo.tables[table][
+ name]['values'].append(None)
+ else: # change status 'add' -> 'update'
self.action = "update"
-
- table = self.mapDBInfo.layers[layer]["table"]
- key = self.mapDBInfo.layers[layer]["key"]
+
+ table = self.mapDBInfo.layers[layer]["table"]
+ key = self.mapDBInfo.layers[layer]["key"]
columns = self.mapDBInfo.tables[table]
-
+
for idx in range(len(columns[key]['values'])):
for name in columns.keys():
if name == key:
cat = int(columns[name]['values'][idx])
break
- # use scrolled panel instead (and fix initial max height of the window to 480px)
- panel = scrolled.ScrolledPanel(parent = self.notebook, id = wx.ID_ANY,
- size = (-1, 150))
- panel.SetupScrolling(scroll_x = False)
-
- self.notebook.AddPage(page = panel, text = " %s %d / %s %d" % (_("Layer"), layer,
- _("Category"), cat))
-
+ # use scrolled panel instead (and fix initial max height of the
+ # window to 480px)
+ panel = scrolled.ScrolledPanel(
+ parent=self.notebook, id=wx.ID_ANY, size=(-1, 150))
+ panel.SetupScrolling(scroll_x=False)
+
+ self.notebook.AddPage(
+ page=panel, text=" %s %d / %s %d" %
+ (_("Layer"), layer, _("Category"), cat))
+
# notebook body
border = wx.BoxSizer(wx.VERTICAL)
-
- flexSizer = wx.FlexGridSizer (cols = 3, hgap = 3, vgap = 3)
+
+ flexSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3)
flexSizer.AddGrowableCol(2)
# columns (sorted by index)
names = [''] * len(columns.keys())
for name in columns.keys():
names[columns[name]['index']] = name
-
+
for name in names:
- if name == key: # skip key column (category)
+ if name == key: # skip key column (category)
continue
-
- vtype = columns[name]['type'].lower()
- ctype = columns[name]['ctype']
-
+
+ vtype = columns[name]['type'].lower()
+ ctype = columns[name]['ctype']
+
if columns[name]['values'][idx] is not None:
if columns[name]['ctype'] != types.StringType:
value = str(columns[name]['values'][idx])
@@ -519,43 +534,51 @@
value = columns[name]['values'][idx]
else:
value = ''
-
- colName = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = name)
- colType = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = "[%s]:" % vtype)
- colValue = wx.TextCtrl(parent = panel, id = wx.ID_ANY, value = value)
+
+ colName = wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label=name)
+ colType = wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label="[%s]:" % vtype)
+ colValue = wx.TextCtrl(
+ parent=panel, id=wx.ID_ANY, value=value)
colValue.SetName(name)
if ctype == int:
colValue.SetValidator(IntegerValidator())
elif ctype == float:
colValue.SetValidator(FloatValidator())
-
+
self.Bind(wx.EVT_TEXT, self.OnSQLStatement, colValue)
if self.action == 'display':
colValue.SetWindowStyle(wx.TE_READONLY)
-
- flexSizer.Add(colName, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL)
- flexSizer.Add(colType, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
- flexSizer.Add(colValue, proportion = 1,
- flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+
+ flexSizer.Add(colName, proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ flexSizer.Add(
+ colType,
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+ flexSizer.Add(colValue, proportion=1,
+ flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
# add widget reference to self.columns
- columns[name]['ids'].append(colValue.GetId()) # name, type, values, id
+ columns[name]['ids'].append(
+ colValue.GetId()) # name, type, values, id
# for each attribute (including category) END
- border.Add(item = flexSizer, proportion = 1, flag = wx.ALL | wx.EXPAND, border = 5)
+ border.Add(
+ item=flexSizer,
+ proportion=1,
+ flag=wx.ALL | wx.EXPAND,
+ border=5)
panel.SetSizer(border)
# for each category END
# for each layer END
-
+
if self.notebook.GetPageCount() == 0:
self.noFoundMsg.Show(True)
else:
self.noFoundMsg.Show(False)
-
+
self.Layout()
-
+
return True
def SetColumnValue(self, layer, column, value):
@@ -566,46 +589,48 @@
"""
table = self.mapDBInfo.GetTable(layer)
columns = self.mapDBInfo.GetTableDesc(table)
-
+
for key, col in columns.iteritems():
if key == column:
- col['values'] = [col['ctype'](value),]
+ col['values'] = [col['ctype'](value), ]
break
-
+
+
class ModifyTableRecord(wx.Dialog):
- def __init__(self, parent, title, data, keyEditable = (-1, True),
- id = wx.ID_ANY, style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+
+ def __init__(self, parent, title, data, keyEditable=(-1, True),
+ id=wx.ID_ANY, style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
"""Dialog for inserting/updating table record
-
+
:param data: a list: [(column, value)]
:param keyEditable: (id, editable?) indicates if textarea for
key column is editable(True) or not
"""
# parent -> VDigitWindow
- wx.Dialog.__init__(self, parent, id, title, style = style)
-
+ wx.Dialog.__init__(self, parent, id, title, style=style)
+
self.CenterOnParent()
-
+
self.keyId = keyEditable[0]
-
- box = wx.StaticBox(parent = self, id = wx.ID_ANY)
+
+ box = wx.StaticBox(parent=self, id=wx.ID_ANY)
box.Hide()
- self.dataPanel = scrolled.ScrolledPanel(parent = self, id = wx.ID_ANY,
- style = wx.TAB_TRAVERSAL)
- self.dataPanel.SetupScrolling(scroll_x = False)
-
+ self.dataPanel = scrolled.ScrolledPanel(parent=self, id=wx.ID_ANY,
+ style=wx.TAB_TRAVERSAL)
+ self.dataPanel.SetupScrolling(scroll_x=False)
+
# buttons
self.btnCancel = wx.Button(self, wx.ID_CANCEL)
self.btnSubmit = wx.Button(self, wx.ID_OK, _("&Submit"))
self.btnSubmit.SetDefault()
-
+
# data area
self.widgets = []
cId = 0
self.usebox = False
self.cat = None
winFocus = False
-
+
for column, ctype, ctypeStr, value in data:
if self.keyId == cId:
self.cat = int(value)
@@ -617,11 +642,12 @@
cId += 1
continue
else:
- valueWin = wx.SpinCtrl(parent = self.dataPanel, id = wx.ID_ANY,
- value = value, min = -1e9, max = 1e9, size = (250, -1))
+ valueWin = wx.SpinCtrl(
+ parent=self.dataPanel, id=wx.ID_ANY, value=value,
+ min=-1e9, max=1e9, size=(250, -1))
else:
- valueWin = wx.TextCtrl(parent = self.dataPanel, id = wx.ID_ANY,
- value = value, size = (250, -1))
+ valueWin = wx.TextCtrl(parent=self.dataPanel, id=wx.ID_ANY,
+ value=value, size=(250, -1))
if ctype == int:
valueWin.SetValidator(IntegerValidator())
elif ctype == float:
@@ -629,116 +655,119 @@
if not winFocus:
wx.CallAfter(valueWin.SetFocus)
winFocus = True
-
- label = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
- label = column)
- ctype = wx.StaticText(parent = self.dataPanel, id = wx.ID_ANY,
- label = "[%s]:" % ctypeStr.lower())
- self.widgets.append((label.GetId(), ctype.GetId(), valueWin.GetId()))
-
+
+ label = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY,
+ label=column)
+ ctype = wx.StaticText(parent=self.dataPanel, id=wx.ID_ANY,
+ label="[%s]:" % ctypeStr.lower())
+ self.widgets.append(
+ (label.GetId(), ctype.GetId(), valueWin.GetId()))
+
cId += 1
-
+
self._layout()
-
+
def _layout(self):
"""Do layout"""
sizer = wx.BoxSizer(wx.VERTICAL)
-
+
# data area
- dataSizer = wx.FlexGridSizer(cols = 3, hgap = 3, vgap = 3)
+ dataSizer = wx.FlexGridSizer(cols=3, hgap=3, vgap=3)
dataSizer.AddGrowableCol(2)
-
+
for labelId, ctypeId, valueId in self.widgets:
label = self.FindWindowById(labelId)
ctype = self.FindWindowById(ctypeId)
value = self.FindWindowById(valueId)
-
- dataSizer.Add(label, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL)
- dataSizer.Add(ctype, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
- dataSizer.Add(value, proportion = 0,
- flag = wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
-
+
+ dataSizer.Add(label, proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL)
+ dataSizer.Add(ctype, proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
+ dataSizer.Add(value, proportion=0,
+ flag=wx.EXPAND | wx.ALIGN_CENTER_VERTICAL)
+
self.dataPanel.SetAutoLayout(True)
self.dataPanel.SetSizer(dataSizer)
dataSizer.Fit(self.dataPanel)
-
+
if self.usebox:
- self.boxSizer.Add(item = self.dataPanel, proportion = 1,
- flag = wx.EXPAND | wx.ALL, border = 5)
-
+ self.boxSizer.Add(item=self.dataPanel, proportion=1,
+ flag=wx.EXPAND | wx.ALL, border=5)
+
# buttons
btnSizer = wx.StdDialogButtonSizer()
btnSizer.AddButton(self.btnCancel)
btnSizer.AddButton(self.btnSubmit)
btnSizer.Realize()
-
+
if not self.usebox:
- sizer.Add(item = self.dataPanel, proportion = 1,
- flag = wx.EXPAND | wx.ALL, border = 5)
+ sizer.Add(item=self.dataPanel, proportion=1,
+ flag=wx.EXPAND | wx.ALL, border=5)
else:
- sizer.Add(item = self.boxSizer, proportion = 1,
- flag = wx.EXPAND | wx.ALL, border = 5)
-
- sizer.Add(item = btnSizer, proportion = 0,
- flag = wx.EXPAND | wx.ALL, border = 5)
-
+ sizer.Add(item=self.boxSizer, proportion=1,
+ flag=wx.EXPAND | wx.ALL, border=5)
+
+ sizer.Add(item=btnSizer, proportion=0,
+ flag=wx.EXPAND | wx.ALL, border=5)
+
framewidth = self.GetBestSize()[0] + 25
self.SetMinSize((framewidth, 250))
self.SetAutoLayout(True)
self.SetSizer(sizer)
sizer.Fit(self)
-
+
self.Layout()
-
- def GetValues(self, columns = None):
+
+ def GetValues(self, columns=None):
"""Return list of values (casted to string).
-
+
If columns is given (list), return only values of given columns.
"""
valueList = list()
for labelId, ctypeId, valueId in self.widgets:
column = self.FindWindowById(labelId).GetLabel()
if columns is None or column in columns:
- value = GetUnicodeValue(self.FindWindowById(valueId).GetValue())
+ value = GetUnicodeValue(
+ self.FindWindowById(valueId).GetValue())
valueList.append(value)
-
+
# add key value
if self.usebox:
valueList.insert(self.keyId, GetUnicodeValue(str(self.cat)))
-
+
return valueList
+
class AddColumnDialog(wx.Dialog):
- def __init__(self, parent, title, id = wx.ID_ANY,
- style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
+
+ def __init__(self, parent, title, id=wx.ID_ANY,
+ style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER):
"""Dialog for adding column into table
"""
- wx.Dialog.__init__(self, parent, id, title, style = style)
-
+ wx.Dialog.__init__(self, parent, id, title, style=style)
+
self.CenterOnParent()
- self.data = {}
- self.data['addColName'] = wx.TextCtrl(parent = self, id = wx.ID_ANY, value = '',
- size = (150, -1), style = wx.TE_PROCESS_ENTER)
+ self.data = {}
+ self.data['addColName'] = wx.TextCtrl(
+ parent=self, id=wx.ID_ANY, value='', size=(
+ 150, -1), style=wx.TE_PROCESS_ENTER)
-
- self.data['addColType'] = wx.Choice (parent = self, id = wx.ID_ANY,
- choices = ["integer",
- "double",
- "varchar",
- "date"]) # FIXME
+ self.data['addColType'] = wx.Choice(parent=self, id=wx.ID_ANY,
+ choices=["integer",
+ "double",
+ "varchar",
+ "date"]) # FIXME
self.data['addColType'].SetSelection(0)
self.data['addColType'].Bind(wx.EVT_CHOICE, self.OnTableChangeType)
-
- self.data['addColLength'] = wx.SpinCtrl(parent = self, id = wx.ID_ANY, size = (65, -1),
- initial = 250,
- min = 1, max = 1e6)
+
+ self.data['addColLength'] = wx.SpinCtrl(
+ parent=self, id=wx.ID_ANY, size=(
+ 65, -1), initial=250, min=1, max=1e6)
self.data['addColLength'].Enable(False)
-
# buttons
self.btnCancel = wx.Button(self, wx.ID_CANCEL)
self.btnOk = wx.Button(self, wx.ID_OK)
@@ -751,37 +780,49 @@
sizer = wx.BoxSizer(wx.VERTICAL)
addSizer = wx.BoxSizer(wx.HORIZONTAL)
- addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Column")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = self.data['addColName'], proportion = 1,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_("Column")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=self.data['addColName'], proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
- addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Type")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = self.data['addColType'],
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_("Type")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=self.data['addColType'],
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
- addSizer.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY, label = _("Length")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
- addSizer.Add(item = self.data['addColLength'],
- flag = wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
+ addSizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_("Length")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+ addSizer.Add(item=self.data['addColLength'],
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
- sizer.Add(item = addSizer, proportion = 0,
- flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+ sizer.Add(item=addSizer, proportion=0,
+ flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
btnSizer = wx.StdDialogButtonSizer()
btnSizer.AddButton(self.btnCancel)
btnSizer.AddButton(self.btnOk)
btnSizer.Realize()
- sizer.Add(item = btnSizer, proportion = 0,
- flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+ sizer.Add(item=btnSizer, proportion=0,
+ flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
self.SetSizer(sizer)
@@ -795,11 +836,11 @@
values['length'] = int(self.data['addColLength'].GetValue())
return values
-
+
def OnTableChangeType(self, event):
"""Data type for new column changed. Enable or disable
data length widget"""
if event.GetString() == "varchar":
self.data['addColLength'].Enable(True)
else:
- self.data['addColLength'].Enable(False)
+ self.data['addColLength'].Enable(False)
Modified: grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/g.gui.dbmgr.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -38,7 +38,7 @@
from grass.script.setup import set_gui_path
set_gui_path()
-
+
from core.utils import _
from dbmgr.manager import AttributeManager
@@ -48,11 +48,13 @@
gscript.fatal(_("Vector map <%s> not found") % options['map'])
app = wx.App()
- gscript.message(_("Loading attribute data for vector map <%s>...") % mapName)
- f = AttributeManager(parent=None, id=wx.ID_ANY,
- title="%s - <%s>" % (_("GRASS GIS Attribute Table Manager"),
- mapName),
- size=(900, 600), vectorName=mapName)
+ gscript.message(
+ _("Loading attribute data for vector map <%s>...") %
+ mapName)
+ f = AttributeManager(
+ parent=None, id=wx.ID_ANY, title="%s - <%s>" %
+ (_("GRASS GIS Attribute Table Manager"), mapName), size=(
+ 900, 600), vectorName=mapName)
f.Show()
app.MainLoop()
Modified: grass/trunk/gui/wxpython/dbmgr/manager.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/manager.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/manager.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -26,21 +26,23 @@
import os
import wx
-import wx.lib.flatnotebook as FN
+import wx.lib.flatnotebook as FN
import grass.script as grass
-from core import globalvar
-from core.gcmd import GMessage
-from core.debug import Debug
+from core import globalvar
+from core.gcmd import GMessage
+from core.debug import Debug
from core.utils import _
-from dbmgr.base import DbMgrBase
+from dbmgr.base import DbMgrBase
from gui_core.widgets import GNotebook
-
+
+
class AttributeManager(wx.Frame, DbMgrBase):
- def __init__(self, parent, id = wx.ID_ANY,
- title = None, vectorName = None, item = None, log = None,
- selection = None, **kwargs):
+
+ def __init__(self, parent, id=wx.ID_ANY,
+ title=None, vectorName=None, item=None, log=None,
+ selection=None, **kwargs):
"""GRASS Attribute Table Manager window
:param parent: parent window
@@ -57,12 +59,12 @@
mapdisplay = self.parent.GetMapDisplay()
except:
mapdisplay = None
-
- DbMgrBase.__init__(self, id = id, mapdisplay = mapdisplay,
- vectorName = vectorName, item = item,
- log = log, statusbar = self,
+
+ DbMgrBase.__init__(self, id=id, mapdisplay=mapdisplay,
+ vectorName=vectorName, item=item,
+ log=log, statusbar=self,
**kwargs)
-
+
wx.Frame.__init__(self, parent, id, *kwargs)
# title
@@ -72,72 +74,86 @@
title += _("READONLY - ")
title += "<%s>" % (self.dbMgrData['vectName'])
+ self.SetTitle(title)
- self.SetTitle(title)
-
# icon
- self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'), wx.BITMAP_TYPE_ICO))
+ self.SetIcon(
+ wx.Icon(
+ os.path.join(
+ globalvar.ICONDIR,
+ 'grass_sql.ico'),
+ wx.BITMAP_TYPE_ICO))
- self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
-
+ self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
if len(self.dbMgrData['mapDBInfo'].layers.keys()) == 0:
- GMessage(parent = self.parent,
- message = _("Database connection for vector map <%s> "
- "is not defined in DB file. "
- "You can define new connection in "
- "'Manage layers' tab.") % self.dbMgrData['vectName'])
-
+ GMessage(
+ parent=self.parent, message=_(
+ "Database connection for vector map <%s> "
+ "is not defined in DB file. "
+ "You can define new connection in "
+ "'Manage layers' tab.") %
+ self.dbMgrData['vectName'])
+
busy = wx.BusyInfo(message=_("Please wait, loading attribute data..."),
parent=self.parent)
wx.SafeYield()
- self.CreateStatusBar(number = 1)
+ self.CreateStatusBar(number=1)
- self.notebook = GNotebook(self.panel, style = globalvar.FNPageDStyle)
-
- self.CreateDbMgrPage(parent = self, pageName = 'browse')
+ self.notebook = GNotebook(self.panel, style=globalvar.FNPageDStyle)
- self.notebook.AddPage(page = self.pages['browse'], text = _("Browse data"),
- name = 'browse')
+ self.CreateDbMgrPage(parent=self, pageName='browse')
+
+ self.notebook.AddPage(page=self.pages['browse'], text=_("Browse data"),
+ name='browse')
self.pages['browse'].SetTabAreaColour(globalvar.FNPageColor)
- self.CreateDbMgrPage(parent = self, pageName = 'manageTable')
+ self.CreateDbMgrPage(parent=self, pageName='manageTable')
- self.notebook.AddPage(page = self.pages['manageTable'], text = _("Manage tables"),
- name = 'table')
+ self.notebook.AddPage(
+ page=self.pages['manageTable'],
+ text=_("Manage tables"),
+ name='table')
self.pages['manageTable'].SetTabAreaColour(globalvar.FNPageColor)
- self.CreateDbMgrPage(parent = self, pageName = 'manageLayer')
- self.notebook.AddPage(page = self.pages['manageLayer'], text = _("Manage layers"),
- name = 'layers')
+ self.CreateDbMgrPage(parent=self, pageName='manageLayer')
+ self.notebook.AddPage(
+ page=self.pages['manageLayer'],
+ text=_("Manage layers"),
+ name='layers')
del busy
if selection:
wx.CallAfter(self.notebook.SetSelectionByName, selection)
else:
- wx.CallAfter(self.notebook.SetSelection, 0) # select browse tab
-
+ wx.CallAfter(self.notebook.SetSelection, 0) # select browse tab
+
# buttons
- self.btnClose = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+ self.btnClose = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
self.btnClose.SetToolTipString(_("Close Attribute Table Manager"))
- self.btnReload = wx.Button(parent = self.panel, id = wx.ID_REFRESH)
- self.btnReload.SetToolTipString(_("Reload currently selected attribute data"))
- self.btnReset = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
- self.btnReset.SetToolTipString(_("Reload all attribute data (drop current selection)"))
-
+ self.btnReload = wx.Button(parent=self.panel, id=wx.ID_REFRESH)
+ self.btnReload.SetToolTipString(
+ _("Reload currently selected attribute data"))
+ self.btnReset = wx.Button(parent=self.panel, id=wx.ID_CLEAR)
+ self.btnReset.SetToolTipString(
+ _("Reload all attribute data (drop current selection)"))
+
# events
- self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
- self.btnReload.Bind(wx.EVT_BUTTON, self.OnReloadData)
- self.btnReset.Bind(wx.EVT_BUTTON, self.OnReloadDataAll)
- self.notebook.Bind(FN.EVT_FLATNOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
+ self.btnClose.Bind(wx.EVT_BUTTON, self.OnCloseWindow)
+ self.btnReload.Bind(wx.EVT_BUTTON, self.OnReloadData)
+ self.btnReset.Bind(wx.EVT_BUTTON, self.OnReloadDataAll)
+ self.notebook.Bind(
+ FN.EVT_FLATNOTEBOOK_PAGE_CHANGED,
+ self.OnPageChanged)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
# do layout
self._layout()
# self.SetMinSize(self.GetBestSize())
- self.SetSize((700, 550)) # FIXME hard-coded size
+ self.SetSize((700, 550)) # FIXME hard-coded size
self.SetMinSize(self.GetSize())
-
+
def _layout(self):
"""Do layout"""
# frame body
@@ -145,36 +161,36 @@
# buttons
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
- btnSizer.Add(item = self.btnReset, proportion = 1,
- flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
- btnSizer.Add(item = self.btnReload, proportion = 1,
- flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
- btnSizer.Add(item = self.btnClose, proportion = 1,
- flag = wx.ALL | wx.ALIGN_RIGHT, border = 5)
+ btnSizer.Add(item=self.btnReset, proportion=1,
+ flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+ btnSizer.Add(item=self.btnReload, proportion=1,
+ flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
+ btnSizer.Add(item=self.btnClose, proportion=1,
+ flag=wx.ALL | wx.ALIGN_RIGHT, border=5)
- mainSizer.Add(item = self.notebook, proportion = 1, flag = wx.EXPAND)
- mainSizer.Add(item = btnSizer, flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
+ mainSizer.Add(item=self.notebook, proportion=1, flag=wx.EXPAND)
+ mainSizer.Add(item=btnSizer, flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
self.panel.SetAutoLayout(True)
self.panel.SetSizer(mainSizer)
mainSizer.Fit(self.panel)
self.Layout()
-
+
def OnCloseWindow(self, event):
"""Cancel button pressed"""
if self.parent and self.parent.GetName() == 'LayerManager':
# deregister ATM
self.parent.dialogs['atm'].remove(self)
-
+
if not isinstance(event, wx.CloseEvent):
self.Destroy()
-
+
event.Skip()
def OnReloadData(self, event):
"""Reload data"""
if self.pages['browse']:
- self.pages['browse'].OnDataReload(event) # TODO replace by signal
+ self.pages['browse'].OnDataReload(event) # TODO replace by signal
def OnReloadDataAll(self, event):
"""Reload all data"""
@@ -191,11 +207,13 @@
id = None
except KeyError:
id = None
-
+
if event.GetSelection() == self.notebook.GetPageIndexByName('browse') and id:
win = self.FindWindowById(id)
if win:
- self.log.write(_("Number of loaded records: %d") % win.GetItemCount())
+ self.log.write(
+ _("Number of loaded records: %d") %
+ win.GetItemCount())
else:
self.log.write("")
self.btnReload.Enable()
@@ -204,14 +222,14 @@
self.log.write("")
self.btnReload.Enable(False)
self.btnReset.Enable(False)
-
- event.Skip()
+ event.Skip()
+
def OnTextEnter(self, event):
pass
def UpdateDialog(self, layer):
"""Updates dialog layout for given layer"""
- DbMgrBase.UpdateDialog(self, layer = layer)
+ DbMgrBase.UpdateDialog(self, layer=layer)
# set current page selection
- self.notebook.SetSelectionByName('layers')
+ self.notebook.SetSelectionByName('layers')
Modified: grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/sqlbuilder.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -33,256 +33,317 @@
from grass.pydispatch.signal import Signal
-from core.gcmd import RunCommand, GError, GMessage
+from core.gcmd import RunCommand, GError, GMessage
from dbmgr.vinfo import CreateDbInfoDesc, VectorDBInfo, GetUnicodeValue
import grass.script as grass
+
class SQLBuilder(wx.Frame):
"""SQLBuider class
Base class for classes, which builds SQL statements.
"""
- def __init__(self, parent, title, vectmap, modeChoices, id = wx.ID_ANY,
- layer = 1):
+
+ def __init__(self, parent, title, vectmap, modeChoices, id=wx.ID_ANY,
+ layer=1):
wx.Frame.__init__(self, parent, id, title)
-
+
self.SetIcon(wx.Icon(os.path.join(globalvar.ICONDIR, 'grass_sql.ico'),
wx.BITMAP_TYPE_ICO))
-
- self.parent = parent
-
+
+ self.parent = parent
+
# variables
- self.vectmap = vectmap # fullname
+ self.vectmap = vectmap # fullname
if not "@" in self.vectmap:
- self.vectmap = grass.find_file(self.vectmap, element = 'vector')['fullname']
+ self.vectmap = grass.find_file(
+ self.vectmap, element='vector')['fullname']
if not self.vectmap:
grass.fatal(_("Vector map <%s> not found") % vectmap)
self.mapname, self.mapset = self.vectmap.split("@", 1)
-
+
# db info
self.layer = layer
self.dbInfo = VectorDBInfo(self.vectmap)
self.tablename = self.dbInfo.GetTable(self.layer)
self.driver, self.database = self.dbInfo.GetDbSettings(self.layer)
-
+
self.colvalues = [] # array with unique values in selected column
-
- self.panel = wx.Panel(parent = self, id = wx.ID_ANY)
+ self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
+
# statusbar
self.statusbar = self.CreateStatusBar(number=1)
-
+
self._doLayout(modeChoices)
self.panel.SetAutoLayout(True)
self.panel.SetSizer(self.pagesizer)
self.pagesizer.Fit(self.panel)
-
+
self.SetMinSize((400, 600))
self.SetClientSize(self.panel.GetSize())
self.CenterOnParent()
-
+
def _doLayout(self, modeChoices):
"""Do dialog layout"""
-
+
self.pagesizer = wx.BoxSizer(wx.VERTICAL)
-
# dbInfo
- databasebox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
- label = " %s " % _("Database connection"))
+ databasebox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+ label=" %s " % _("Database connection"))
databaseboxsizer = wx.StaticBoxSizer(databasebox, wx.VERTICAL)
- databaseboxsizer.Add(item = CreateDbInfoDesc(self.panel, self.dbInfo, layer = self.layer),
- proportion=1,
- flag=wx.EXPAND | wx.ALL,
- border=3)
+ databaseboxsizer.Add(
+ item=CreateDbInfoDesc(
+ self.panel,
+ self.dbInfo,
+ layer=self.layer),
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=3)
#
# text areas
#
# sql box
- sqlbox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
- label = " %s " % _("Query"))
+ sqlbox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+ label=" %s " % _("Query"))
sqlboxsizer = wx.StaticBoxSizer(sqlbox, wx.VERTICAL)
- self.text_sql = wx.TextCtrl(parent = self.panel, id = wx.ID_ANY,
- value = '', size = (-1, 50),
+ self.text_sql = wx.TextCtrl(parent=self.panel, id=wx.ID_ANY,
+ value='', size=(-1, 50),
style=wx.TE_MULTILINE)
-
+
self.text_sql.SetInsertionPointEnd()
wx.CallAfter(self.text_sql.SetFocus)
- sqlboxsizer.Add(item = self.text_sql, flag = wx.EXPAND)
-
+ sqlboxsizer.Add(item=self.text_sql, flag=wx.EXPAND)
+
#
# buttons
#
- self.btn_clear = wx.Button(parent = self.panel, id = wx.ID_CLEAR)
+ self.btn_clear = wx.Button(parent=self.panel, id=wx.ID_CLEAR)
self.btn_clear.SetToolTipString(_("Set SQL statement to default"))
- self.btn_apply = wx.Button(parent = self.panel, id = wx.ID_APPLY)
- self.btn_apply.SetToolTipString(_("Apply SQL statement in Attribute Table Manager"))
- self.btn_close = wx.Button(parent = self.panel, id = wx.ID_CLOSE)
+ self.btn_apply = wx.Button(parent=self.panel, id=wx.ID_APPLY)
+ self.btn_apply.SetToolTipString(
+ _("Apply SQL statement in Attribute Table Manager"))
+ self.btn_close = wx.Button(parent=self.panel, id=wx.ID_CLOSE)
self.btn_close.SetToolTipString(_("Close the dialog"))
-
- self.btn_logic = { 'is' : ['=', ],
- 'isnot' : ['!=', ],
- 'like' : ['LIKE', ],
- 'gt' : ['>', ],
- 'ge' : ['>=', ],
- 'lt' : ['<', ],
- 'le' : ['<=', ],
- 'or' : ['OR', ],
- 'not' : ['NOT', ],
- 'and' : ['AND', ],
- 'brac' : ['()', ],
- 'prc' : ['%', ] }
-
- self.btn_logicpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
+
+ self.btn_logic = {'is': ['=', ],
+ 'isnot': ['!=', ],
+ 'like': ['LIKE', ],
+ 'gt': ['>', ],
+ 'ge': ['>=', ],
+ 'lt': ['<', ],
+ 'le': ['<=', ],
+ 'or': ['OR', ],
+ 'not': ['NOT', ],
+ 'and': ['AND', ],
+ 'brac': ['()', ],
+ 'prc': ['%', ]}
+
+ self.btn_logicpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
for key, value in self.btn_logic.iteritems():
- btn = wx.Button(parent = self.btn_logicpanel, id = wx.ID_ANY,
- label = value[0])
+ btn = wx.Button(parent=self.btn_logicpanel, id=wx.ID_ANY,
+ label=value[0])
self.btn_logic[key].append(btn.GetId())
-
- self.buttonsizer = wx.FlexGridSizer(cols = 4, hgap = 5, vgap = 5)
- self.buttonsizer.Add(item = self.btn_clear)
- self.buttonsizer.Add(item = self.btn_apply)
- self.buttonsizer.Add(item = self.btn_close)
-
+
+ self.buttonsizer = wx.FlexGridSizer(cols=4, hgap=5, vgap=5)
+ self.buttonsizer.Add(item=self.btn_clear)
+ self.buttonsizer.Add(item=self.btn_apply)
+ self.buttonsizer.Add(item=self.btn_close)
+
btn_logicsizer = wx.GridBagSizer(5, 5)
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['is'][1]), pos = (0,0))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['isnot'][1]), pos = (1,0))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['like'][1]), pos = (2, 0))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['is'][1]), pos=(
+ 0, 0))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['isnot'][1]), pos=(
+ 1, 0))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['like'][1]), pos=(
+ 2, 0))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['gt'][1]), pos = (0, 1))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['ge'][1]), pos = (1, 1))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['or'][1]), pos = (2, 1))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['gt'][1]), pos=(
+ 0, 1))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['ge'][1]), pos=(
+ 1, 1))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['or'][1]), pos=(
+ 2, 1))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['lt'][1]), pos = (0, 2))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['le'][1]), pos = (1, 2))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['not'][1]), pos = (2, 2))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['lt'][1]), pos=(
+ 0, 2))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['le'][1]), pos=(
+ 1, 2))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['not'][1]), pos=(
+ 2, 2))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['brac'][1]), pos = (0, 3))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['prc'][1]), pos = (1, 3))
- btn_logicsizer.Add(item = self.FindWindowById(self.btn_logic['and'][1]), pos = (2, 3))
-
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['brac'][1]), pos=(
+ 0, 3))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['prc'][1]), pos=(
+ 1, 3))
+ btn_logicsizer.Add(
+ item=self.FindWindowById(
+ self.btn_logic['and'][1]), pos=(
+ 2, 3))
+
self.btn_logicpanel.SetSizer(btn_logicsizer)
#
# list boxes (columns, values)
#
self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
-
- columnsbox = wx.StaticBox(parent = self.panel, id = wx.ID_ANY,
- label = " %s " % _("Columns"))
+
+ columnsbox = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
+ label=" %s " % _("Columns"))
columnsizer = wx.StaticBoxSizer(columnsbox, wx.VERTICAL)
- self.list_columns = wx.ListBox(parent = self.panel, id = wx.ID_ANY,
- choices = self.dbInfo.GetColumns(self.tablename),
- style = wx.LB_MULTIPLE)
- columnsizer.Add(item = self.list_columns, proportion = 1,
- flag = wx.EXPAND)
+ self.list_columns = wx.ListBox(
+ parent=self.panel,
+ id=wx.ID_ANY,
+ choices=self.dbInfo.GetColumns(
+ self.tablename),
+ style=wx.LB_MULTIPLE)
+ columnsizer.Add(item=self.list_columns, proportion=1,
+ flag=wx.EXPAND)
modesizer = wx.BoxSizer(wx.VERTICAL)
-
- self.mode = wx.RadioBox(parent = self.panel, id = wx.ID_ANY,
- label = " %s " % _("Interactive insertion"),
- choices = modeChoices,
- style = wx.RA_SPECIFY_COLS,
- majorDimension = 1)
- self.mode.SetSelection(1) # default 'values'
- modesizer.Add(item = self.mode, proportion = 1,
- flag = wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, border = 5)
+ self.mode = wx.RadioBox(parent=self.panel, id=wx.ID_ANY,
+ label=" %s " % _("Interactive insertion"),
+ choices=modeChoices,
+ style=wx.RA_SPECIFY_COLS,
+ majorDimension=1)
+ self.mode.SetSelection(1) # default 'values'
+ modesizer.Add(item=self.mode, proportion=1,
+ flag=wx.ALIGN_CENTER_HORIZONTAL | wx.EXPAND, border=5)
+
# self.list_columns.SetMinSize((-1,130))
# self.list_values.SetMinSize((-1,100))
- self.valuespanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
- valuesbox = wx.StaticBox(parent = self.valuespanel, id = wx.ID_ANY,
- label = " %s " % _("Values"))
+ self.valuespanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
+ valuesbox = wx.StaticBox(parent=self.valuespanel, id=wx.ID_ANY,
+ label=" %s " % _("Values"))
valuesizer = wx.StaticBoxSizer(valuesbox, wx.VERTICAL)
- self.list_values = wx.ListBox(parent = self.valuespanel, id = wx.ID_ANY,
- choices = self.colvalues,
- style = wx.LB_MULTIPLE)
- valuesizer.Add(item = self.list_values, proportion = 1,
- flag = wx.EXPAND)
+ self.list_values = wx.ListBox(parent=self.valuespanel, id=wx.ID_ANY,
+ choices=self.colvalues,
+ style=wx.LB_MULTIPLE)
+ valuesizer.Add(item=self.list_values, proportion=1,
+ flag=wx.EXPAND)
self.valuespanel.SetSizer(valuesizer)
- self.btn_unique = wx.Button(parent = self.valuespanel, id = wx.ID_ANY,
- label = _("Get all values"))
+ self.btn_unique = wx.Button(parent=self.valuespanel, id=wx.ID_ANY,
+ label=_("Get all values"))
self.btn_unique.Enable(False)
- self.btn_uniquesample = wx.Button(parent = self.valuespanel, id = wx.ID_ANY,
- label = _("Get sample"))
- self.btn_uniquesample.SetToolTipString(_("Get first 256 unique values as sample"))
+ self.btn_uniquesample = wx.Button(
+ parent=self.valuespanel,
+ id=wx.ID_ANY,
+ label=_("Get sample"))
+ self.btn_uniquesample.SetToolTipString(
+ _("Get first 256 unique values as sample"))
self.btn_uniquesample.Enable(False)
buttonsizer3 = wx.BoxSizer(wx.HORIZONTAL)
- buttonsizer3.Add(item = self.btn_uniquesample, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL | wx.RIGHT, border = 5)
- buttonsizer3.Add(item = self.btn_unique, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL)
+ buttonsizer3.Add(item=self.btn_uniquesample, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL | wx.RIGHT, border=5)
+ buttonsizer3.Add(item=self.btn_unique, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL)
- valuesizer.Add(item = buttonsizer3, proportion = 0,
- flag = wx.TOP, border = 5)
+ valuesizer.Add(item=buttonsizer3, proportion=0,
+ flag=wx.TOP, border=5)
# go to
gotosizer = wx.BoxSizer(wx.HORIZONTAL)
- self.goto = wx.TextCtrl(parent = self.valuespanel, id = wx.ID_ANY, style = wx.TE_PROCESS_ENTER)
- gotosizer.Add(item = wx.StaticText(parent = self.valuespanel, id = wx.ID_ANY,
- label = _("Go to:")), proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border = 5)
- gotosizer.Add(item = self.goto, proportion = 1,
- flag = wx.EXPAND)
- valuesizer.Add(item = gotosizer, proportion = 0,
- flag = wx.ALL | wx.EXPAND, border = 5)
-
- self.hsizer.Add(item = columnsizer, proportion = 1,
- flag = wx.EXPAND)
- self.hsizer.Add(item = self.valuespanel, proportion = 1,
- flag = wx.EXPAND)
+ self.goto = wx.TextCtrl(
+ parent=self.valuespanel,
+ id=wx.ID_ANY,
+ style=wx.TE_PROCESS_ENTER)
+ gotosizer.Add(item=wx.StaticText(parent=self.valuespanel, id=wx.ID_ANY,
+ label=_("Go to:")), proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border=5)
+ gotosizer.Add(item=self.goto, proportion=1,
+ flag=wx.EXPAND)
+ valuesizer.Add(item=gotosizer, proportion=0,
+ flag=wx.ALL | wx.EXPAND, border=5)
- self.close_onapply = wx.CheckBox(parent = self.panel, id = wx.ID_ANY,
- label = _("Close dialog on apply"))
+ self.hsizer.Add(item=columnsizer, proportion=1,
+ flag=wx.EXPAND)
+ self.hsizer.Add(item=self.valuespanel, proportion=1,
+ flag=wx.EXPAND)
+
+ self.close_onapply = wx.CheckBox(parent=self.panel, id=wx.ID_ANY,
+ label=_("Close dialog on apply"))
self.close_onapply.SetValue(True)
-
- self.pagesizer.Add(item = databaseboxsizer,
- flag = wx.ALL | wx.EXPAND, border = 5)
- self.pagesizer.Add(item = modesizer, proportion = 0,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
- self.pagesizer.Add(item = self.hsizer, proportion = 1,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
+
+ self.pagesizer.Add(item=databaseboxsizer,
+ flag=wx.ALL | wx.EXPAND, border=5)
+ self.pagesizer.Add(
+ item=modesizer,
+ proportion=0,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ border=5)
+ self.pagesizer.Add(
+ item=self.hsizer,
+ proportion=1,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ border=5)
# self.pagesizer.Add(self.btn_uniqe,0,wx.ALIGN_LEFT|wx.TOP,border=5)
# self.pagesizer.Add(self.btn_uniqesample,0,wx.ALIGN_LEFT|wx.TOP,border=5)
- self.pagesizer.Add(item = self.btn_logicpanel, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL)
- self.pagesizer.Add(item = sqlboxsizer, proportion = 0,
- flag = wx.EXPAND | wx.LEFT | wx.RIGHT, border = 5)
- self.pagesizer.Add(item = self.buttonsizer, proportion = 0,
- flag = wx.ALIGN_RIGHT | wx.ALL, border = 5)
- self.pagesizer.Add(item = self.close_onapply, proportion = 0,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-
+ self.pagesizer.Add(item=self.btn_logicpanel, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL)
+ self.pagesizer.Add(item=sqlboxsizer, proportion=0,
+ flag=wx.EXPAND | wx.LEFT | wx.RIGHT, border=5)
+ self.pagesizer.Add(item=self.buttonsizer, proportion=0,
+ flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+ self.pagesizer.Add(
+ item=self.close_onapply,
+ proportion=0,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND,
+ border=5)
+
#
# bindings
#
self.mode.Bind(wx.EVT_RADIOBOX, self.OnMode)
- #self.text_sql.Bind(wx.EVT_ACTIVATE, self.OnTextSqlActivate)TODO
+ # self.text_sql.Bind(wx.EVT_ACTIVATE, self.OnTextSqlActivate)TODO
- self.btn_unique.Bind(wx.EVT_BUTTON, self.OnUniqueValues)
+ self.btn_unique.Bind(wx.EVT_BUTTON, self.OnUniqueValues)
self.btn_uniquesample.Bind(wx.EVT_BUTTON, self.OnSampleValues)
-
+
for key, value in self.btn_logic.iteritems():
self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)
-
- self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
- self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
- self.btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
- self.list_columns.Bind(wx.EVT_LISTBOX, self.OnAddColumn)
- self.list_values.Bind(wx.EVT_LISTBOX, self.OnAddValue)
- self.goto.Bind(wx.EVT_TEXT, self.OnGoTo)
- self.goto.Bind(wx.EVT_TEXT_ENTER, self.OnAddValue)
+ self.btn_close.Bind(wx.EVT_BUTTON, self.OnClose)
+ self.btn_clear.Bind(wx.EVT_BUTTON, self.OnClear)
+ self.btn_apply.Bind(wx.EVT_BUTTON, self.OnApply)
- def OnUniqueValues(self, event, justsample = False):
+ self.list_columns.Bind(wx.EVT_LISTBOX, self.OnAddColumn)
+ self.list_values.Bind(wx.EVT_LISTBOX, self.OnAddValue)
+ self.goto.Bind(wx.EVT_TEXT, self.OnGoTo)
+ self.goto.Bind(wx.EVT_TEXT_ENTER, self.OnAddValue)
+
+ def OnUniqueValues(self, event, justsample=False):
"""Get unique values"""
vals = []
try:
@@ -291,29 +352,34 @@
except:
self.list_values.Clear()
return
-
+
self.list_values.Clear()
-
- data = grass.db_select(sql = "SELECT %s FROM %s" % (column, self.tablename),
- database = self.database,
- driver = self.driver, sep = '{_sep_}')
+
+ data = grass.db_select(
+ sql="SELECT %s FROM %s" %
+ (column,
+ self.tablename),
+ database=self.database,
+ driver=self.driver,
+ sep='{_sep_}')
if not data:
return
-
- desc = self.dbInfo.GetTableDesc(self.dbInfo.GetTable(self.layer))[column]
-
+
+ desc = self.dbInfo.GetTableDesc(
+ self.dbInfo.GetTable(self.layer))[column]
+
i = 0
for item in sorted(set(map(lambda x: desc['ctype'](x[0]), data))):
if justsample and i > 255:
break
-
+
if desc['type'] != 'character':
item = str(item)
else:
item = GetUnicodeValue(item)
self.list_values.Append(item)
i += 1
-
+
def OnSampleValues(self, event):
"""Get sample values"""
self.OnUniqueValues(None, True)
@@ -323,12 +389,12 @@
idx = self.list_columns.GetSelections()
for i in idx:
column = self.list_columns.GetString(i)
- self._add(element = 'column', value = column)
-
+ self._add(element='column', value=column)
+
if not self.btn_uniquesample.IsEnabled():
self.btn_uniquesample.Enable(True)
self.btn_unique.Enable(True)
-
+
def OnAddValue(self, event):
"""Add value"""
selection = self.list_values.GetSelections()
@@ -340,19 +406,21 @@
value = self.list_values.GetString(idx)
idx = self.list_columns.GetSelections()[0]
column = self.list_columns.GetString(idx)
-
- ctype = self.dbInfo.GetTableDesc(self.dbInfo.GetTable(self.layer))[column]['type']
-
+
+ ctype = self.dbInfo.GetTableDesc(
+ self.dbInfo.GetTable(
+ self.layer))[column]['type']
+
if ctype == 'character':
value = "'%s'" % value
-
- self._add(element = 'value', value = value)
+ self._add(element='value', value=value)
+
def OnGoTo(self, event):
# clear all previous selections
for item in self.list_values.GetSelections():
self.list_values.Deselect(item)
-
+
gotoText = event.GetString()
lenLimit = len(gotoText)
found = idx = 0
@@ -364,7 +432,7 @@
if found > 0:
self.list_values.SetSelection(found)
-
+
def OnAddMark(self, event):
"""Add mark"""
mark = None
@@ -372,58 +440,61 @@
self.btn_logicpanel.IsShown():
btns = self.btn_logic
elif self.btn_arithmeticpanel and \
- self.btn_arithmeticpanel.IsShown():
+ self.btn_arithmeticpanel.IsShown():
btns = self.btn_arithmetic
-
+
for key, value in btns.iteritems():
if event.GetId() == value[1]:
mark = value[0]
break
-
- self._add(element = 'mark', value = mark)
+ self._add(element='mark', value=mark)
+
def GetSQLStatement(self):
"""Return SQL statement"""
- return self.text_sql.GetValue().strip().replace("\n"," ")
-
+ return self.text_sql.GetValue().strip().replace("\n", " ")
+
def OnClose(self, event):
self.Destroy()
event.Skip()
-
+
+
class SQLBuilderSelect(SQLBuilder):
"""Class for building SELECT SQL statement"""
- def __init__(self, parent, vectmap, id = wx.ID_ANY,
- layer = 1, evtHandler = None):
+ def __init__(self, parent, vectmap, id=wx.ID_ANY,
+ layer=1, evtHandler=None):
+
self.evtHandler = evtHandler
# set dialog title
title = _("GRASS SQL Builder (%(type)s) - <%(map)s>") % \
- { 'type' : "SELECT", 'map' : vectmap }
+ {'type': "SELECT", 'map': vectmap}
- modeChoices = [_("Column to show (SELECT clause)"),
+ modeChoices = [_("Column to show (SELECT clause)"),
_("Constraint for query (WHERE clause)")]
- SQLBuilder.__init__(self, parent, title, vectmap, id = wx.ID_ANY,
- modeChoices = modeChoices, layer = layer)
+ SQLBuilder.__init__(self, parent, title, vectmap, id=wx.ID_ANY,
+ modeChoices=modeChoices, layer=layer)
-
def _doLayout(self, modeChoices):
"""Do dialog layout"""
SQLBuilder._doLayout(self, modeChoices)
self.text_sql.SetValue("SELECT * FROM %s" % self.tablename)
- self.text_sql.SetToolTipString(_("Example: %s") % "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' OR OBJECTID < 10")
+ self.text_sql.SetToolTipString(
+ _("Example: %s") %
+ "SELECT * FROM roadsmajor WHERE MULTILANE = 'no' OR OBJECTID < 10")
- self.btn_verify = wx.Button(parent = self.panel, id = wx.ID_ANY,
- label = _("Verify"))
+ self.btn_verify = wx.Button(parent=self.panel, id=wx.ID_ANY,
+ label=_("Verify"))
self.btn_verify.SetToolTipString(_("Verify SQL statement"))
- self.buttonsizer.Insert(item = self.btn_verify, before = 1)
-
+ self.buttonsizer.Insert(item=self.btn_verify, before=1)
+
self.text_sql.Bind(wx.EVT_TEXT, self.OnText)
- self.btn_verify.Bind(wx.EVT_BUTTON, self.OnVerify)
+ self.btn_verify.Bind(wx.EVT_BUTTON, self.OnVerify)
self.text_sql.SetInsertionPoint(self.text_sql.GetLastPosition())
self.statusbar.SetStatusText(_("SQL statement not verified"), 0)
@@ -431,11 +502,11 @@
def OnApply(self, event):
"""Apply button pressed"""
if self.evtHandler:
- self.evtHandler(event = 'apply')
-
+ self.evtHandler(event='apply')
+
if self.close_onapply.IsChecked():
self.Destroy()
-
+
event.Skip()
def OnClear(self, event):
@@ -448,8 +519,8 @@
self.valuespanel.Hide()
self.btn_logicpanel.Hide()
elif self.mode.GetSelection() == 1:
- self.valuespanel.Show()
- self.btn_logicpanel.Show()
+ self.valuespanel.Show()
+ self.btn_logicpanel.Show()
self.pagesizer.Layout()
def OnText(self, event):
@@ -458,21 +529,21 @@
self.btn_verify.Enable(True)
else:
self.btn_verify.Enable(False)
-
+
def OnVerify(self, event):
"""Verify button pressed"""
ret, msg = RunCommand('db.select',
- getErrorMsg = True,
- table = self.tablename,
- sql = self.text_sql.GetValue(),
- flags = 't',
- driver = self.driver,
- database = self.database)
-
+ getErrorMsg=True,
+ table=self.tablename,
+ sql=self.text_sql.GetValue(),
+ flags='t',
+ driver=self.driver,
+ database=self.database)
+
if ret != 0 and msg:
self.statusbar.SetStatusText(_("SQL statement is not valid"), 0)
- GError(parent = self,
- message = _("SQL statement is not valid.\n\n%s") % msg)
+ GError(parent=self,
+ message=_("SQL statement is not valid.\n\n%s") % msg)
else:
self.statusbar.SetStatusText(_("SQL statement is valid"), 0)
@@ -485,7 +556,7 @@
curspos = self.text_sql.GetInsertionPoint()
newsqlstr = ''
if element == 'column':
- if self.mode.GetSelection() == 0: # -> column
+ if self.mode.GetSelection() == 0: # -> column
idx1 = len('select')
idx2 = sqlstr.lower().find('from')
colstr = sqlstr[idx1:idx2].strip()
@@ -494,28 +565,28 @@
else:
cols = colstr.split(',')
if value in cols:
- cols.remove(value)
+ cols.remove(value)
else:
cols.append(value)
-
+
if len(cols) < 1:
- cols = ['*',]
+ cols = ['*', ]
newsqlstr = 'SELECT ' + ','.join(cols) + ' '
curspos = len(newsqlstr)
newsqlstr += sqlstr[idx2:]
- else: # -> where
+ else: # -> where
newsqlstr = ''
if sqlstr.lower().find('where') < 0:
- newsqlstr += ' WHERE'
+ newsqlstr += ' WHERE'
newsqlstr += ' ' + value
curspos = self.text_sql.GetLastPosition() + len(newsqlstr)
newsqlstr = sqlstr + newsqlstr
- elif element in ['value', 'mark']:
+ elif element in ['value', 'mark']:
addstr = ' ' + value + ' '
newsqlstr = sqlstr[:curspos] + addstr + sqlstr[curspos:]
curspos += len(addstr)
-
+
if newsqlstr:
self.text_sql.SetValue(newsqlstr)
@@ -529,30 +600,32 @@
def OnClose(self, event):
"""Close button pressed"""
if self.evtHandler:
- self.evtHandler(event = 'close')
-
+ self.evtHandler(event='close')
+
SQLBuilder.OnClose(self, event)
+
class SQLBuilderUpdate(SQLBuilder):
"""Class for building UPDATE SQL statement"""
- def __init__(self, parent, vectmap, id = wx.ID_ANY,
- layer = 1, column = None):
- self.column = column
+ def __init__(self, parent, vectmap, id=wx.ID_ANY,
+ layer=1, column=None):
+
+ self.column = column
# set dialog title
title = _("GRASS SQL Builder (%(type)s) - <%(map)s>") % \
- { 'type' : "UPDATE", 'map' : vectmap }
+ {'type': "UPDATE", 'map': vectmap}
- modeChoices = [_("Column to set (SET clause)"),
- _("Constraint for query (WHERE clause)"),
+ modeChoices = [_("Column to set (SET clause)"),
+ _("Constraint for query (WHERE clause)"),
_("Calculate column value to set")]
- SQLBuilder.__init__(self, parent, title, vectmap, id = wx.ID_ANY,
- modeChoices = modeChoices, layer = layer)
+ SQLBuilder.__init__(self, parent, title, vectmap, id=wx.ID_ANY,
+ modeChoices=modeChoices, layer=layer)
# signals
self.sqlApplied = Signal("SQLBuilder.sqlApplied")
- if parent: # TODO: replace by giface
+ if parent: # TODO: replace by giface
self.sqlApplied.connect(parent.Update)
def _doLayout(self, modeChoices):
@@ -562,61 +635,78 @@
self.initText = "UPDATE %s SET" % self.tablename
if self.column:
- self.initText += " %s = " % self.column
+ self.initText += " %s = " % self.column
self.text_sql.SetValue(self.initText)
- self.btn_arithmetic = { 'eq' : ['=', ],
- 'brac' : ['()',],
- 'plus' : ['+', ],
- 'minus' : ['-', ],
- 'divide' : ['/', ],
- 'multiply' : ['*', ]}
+ self.btn_arithmetic = {'eq': ['=', ],
+ 'brac': ['()', ],
+ 'plus': ['+', ],
+ 'minus': ['-', ],
+ 'divide': ['/', ],
+ 'multiply': ['*', ]}
- self.btn_arithmeticpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
+ self.btn_arithmeticpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
for key, value in self.btn_arithmetic.iteritems():
- btn = wx.Button(parent = self.btn_arithmeticpanel, id = wx.ID_ANY,
- label = value[0])
+ btn = wx.Button(parent=self.btn_arithmeticpanel, id=wx.ID_ANY,
+ label=value[0])
self.btn_arithmetic[key].append(btn.GetId())
- btn_arithmeticsizer = wx.GridBagSizer(hgap = 5, vgap = 5)
+ btn_arithmeticsizer = wx.GridBagSizer(hgap=5, vgap=5)
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['eq'][1]), pos = (0, 0))
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['brac'][1]), pos = (1, 0))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['eq'][1]), pos=(
+ 0, 0))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['brac'][1]), pos=(
+ 1, 0))
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['plus'][1]), pos = (0, 1))
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['minus'][1]), pos = (1, 1))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['plus'][1]), pos=(
+ 0, 1))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['minus'][1]), pos=(
+ 1, 1))
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['divide'][1]), pos = (0, 2))
- btn_arithmeticsizer.Add(item = self.FindWindowById(self.btn_arithmetic['multiply'][1]), pos = (1, 2))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['divide'][1]), pos=(
+ 0, 2))
+ btn_arithmeticsizer.Add(
+ item=self.FindWindowById(
+ self.btn_arithmetic['multiply'][1]), pos=(
+ 1, 2))
self.btn_arithmeticpanel.SetSizer(btn_arithmeticsizer)
- self.pagesizer.Insert(item = self.btn_arithmeticpanel, before = 3,
- proportion = 0, flag = wx.ALIGN_CENTER_HORIZONTAL)
+ self.pagesizer.Insert(item=self.btn_arithmeticpanel, before=3,
+ proportion=0, flag=wx.ALIGN_CENTER_HORIZONTAL)
-
- self.funcpanel = wx.Panel(parent = self.panel, id = wx.ID_ANY)
+ self.funcpanel = wx.Panel(parent=self.panel, id=wx.ID_ANY)
self._initSqlFunctions()
- funcsbox = wx.StaticBox(parent = self.funcpanel, id = wx.ID_ANY,
- label = " %s " % _("Functions"))
+ funcsbox = wx.StaticBox(parent=self.funcpanel, id=wx.ID_ANY,
+ label=" %s " % _("Functions"))
funcsizer = wx.StaticBoxSizer(funcsbox, wx.VERTICAL)
- self.list_func = wx.ListBox(parent = self.funcpanel, id = wx.ID_ANY,
- choices = self.sqlFuncs['sqlite'].keys(),
- style = wx.LB_SORT)
+ self.list_func = wx.ListBox(parent=self.funcpanel, id=wx.ID_ANY,
+ choices=self.sqlFuncs['sqlite'].keys(),
+ style=wx.LB_SORT)
- funcsizer.Add(item = self.list_func, proportion = 1,
- flag = wx.EXPAND)
+ funcsizer.Add(item=self.list_func, proportion=1,
+ flag=wx.EXPAND)
self.funcpanel.SetSizer(funcsizer)
- self.hsizer.Insert(item = self.funcpanel, before = 2,
- proportion = 1, flag = wx.EXPAND)
+ self.hsizer.Insert(item=self.funcpanel, before=2,
+ proportion=1, flag=wx.EXPAND)
- self.list_func.Bind(wx.EVT_LISTBOX, self.OnAddFunc)
+ self.list_func.Bind(wx.EVT_LISTBOX, self.OnAddFunc)
for key, value in self.btn_arithmetic.iteritems():
- self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)
+ self.FindWindowById(value[1]).Bind(wx.EVT_BUTTON, self.OnAddMark)
self.mode.SetSelection(0)
self.OnMode(None)
self.text_sql.SetInsertionPoint(self.text_sql.GetLastPosition())
@@ -625,18 +715,18 @@
"""Apply button pressed"""
ret, msg = RunCommand('db.execute',
- getErrorMsg = True,
- parent = self,
- stdin = self.text_sql.GetValue(),
- input = '-',
- driver = self.driver,
- database = self.database)
+ getErrorMsg=True,
+ parent=self,
+ stdin=self.text_sql.GetValue(),
+ input='-',
+ driver=self.driver,
+ database=self.database)
if ret != 0 and msg:
self.statusbar.SetStatusText(_("SQL statement was not applied"), 0)
else:
self.statusbar.SetStatusText(_("SQL statement applied"), 0)
-
+
self.sqlApplied.emit()
def OnClear(self, event):
@@ -651,31 +741,31 @@
self.btn_arithmeticpanel.Hide()
self.funcpanel.Hide()
elif self.mode.GetSelection() == 1:
- self.valuespanel.Show()
- self.btn_logicpanel.Show()
- self.btn_arithmeticpanel.Hide()
- self.funcpanel.Hide()
+ self.valuespanel.Show()
+ self.btn_logicpanel.Show()
+ self.btn_arithmeticpanel.Hide()
+ self.funcpanel.Hide()
elif self.mode.GetSelection() == 2:
- self.valuespanel.Hide()
- self.btn_logicpanel.Hide()
- self.btn_arithmeticpanel.Show()
- self.funcpanel.Show()
+ self.valuespanel.Hide()
+ self.btn_logicpanel.Hide()
+ self.btn_arithmeticpanel.Show()
+ self.funcpanel.Show()
self.pagesizer.Layout()
-
def OnAddFunc(self, event):
"""Add function to the query"""
if self.driver == 'dbf':
- GMessage(parent = self,
- message = _("Dbf driver does not support usage of SQL functions."))
+ GMessage(
+ parent=self,
+ message=_(
+ "Dbf driver does not support usage of SQL functions."))
return
idx = self.list_func.GetSelections()
for i in idx:
- func = self.sqlFuncs['sqlite'][self.list_func.GetString(i)][0]
- self._add(element = 'func', value = func)
-
+ func = self.sqlFuncs['sqlite'][self.list_func.GetString(i)][0]
+ self._add(element='func', value=func)
def _add(self, element, value):
"""Add element to the query
@@ -687,41 +777,41 @@
newsqlstr = ''
if element in ['value', 'mark', 'func'] or \
- (element == 'column' and self.mode.GetSelection() == 2):
+ (element == 'column' and self.mode.GetSelection() == 2):
addstr = ' ' + value + ' '
newsqlstr = sqlstr[:curspos] + addstr + sqlstr[curspos:]
curspos += len(addstr)
elif element == 'column':
- if self.mode.GetSelection() == 0: # -> column
+ if self.mode.GetSelection() == 0: # -> column
idx1 = sqlstr.lower().find('set') + len('set')
idx2 = sqlstr.lower().find('where')
- if idx2 >= 0:
+ if idx2 >= 0:
colstr = sqlstr[idx1:idx2].strip()
else:
colstr = sqlstr[idx1:].strip()
-
- cols = [col.split('=')[0].strip() for col in colstr.split(',')]
+
+ cols = [col.split('=')[0].strip() for col in colstr.split(',')]
if unicode(value) in cols:
self.text_sql.SetInsertionPoint(curspos)
- wx.CallAfter(self.text_sql.SetFocus)
+ wx.CallAfter(self.text_sql.SetFocus)
return
if colstr:
colstr += ','
colstr = ' ' + colstr
colstr += ' ' + value + '= '
newsqlstr = sqlstr[:idx1] + colstr
- if idx2 >= 0:
+ if idx2 >= 0:
newsqlstr += sqlstr[idx2:]
curspos = idx1 + len(colstr)
- elif self.mode.GetSelection() == 1: # -> where
+ elif self.mode.GetSelection() == 1: # -> where
newsqlstr = ''
if sqlstr.lower().find('where') < 0:
newsqlstr += ' WHERE'
newsqlstr += ' ' + value
curspos = self.text_sql.GetLastPosition() + len(newsqlstr)
- newsqlstr = sqlstr + newsqlstr
+ newsqlstr = sqlstr + newsqlstr
if newsqlstr:
self.text_sql.SetValue(newsqlstr)
@@ -734,22 +824,22 @@
self.sqlFuncs = {}
# TODO add functions for other drivers
self.sqlFuncs['sqlite'] = {
- 'ABS' : ['ABS()'],
- 'LENGTH' : ['LENGTH()'],
- 'LOWER' : ['LOWER()'],
- 'LTRIM' : ['LTRIM(,)'],
- 'MAX' : ['MAX()'],
- 'MIN' : ['MIN()'],
- 'RTRIM' : ['RTRIM(,)'],
- 'SUBSTR' : ['SUBSTR (,[,])'],
- 'TRIM' : ['TRIM (,)']
- }
+ 'ABS': ['ABS()'],
+ 'LENGTH': ['LENGTH()'],
+ 'LOWER': ['LOWER()'],
+ 'LTRIM': ['LTRIM(,)'],
+ 'MAX': ['MAX()'],
+ 'MIN': ['MIN()'],
+ 'RTRIM': ['RTRIM(,)'],
+ 'SUBSTR': ['SUBSTR (,[,])'],
+ 'TRIM': ['TRIM (,)']
+ }
if __name__ == "__main__":
if len(sys.argv) not in [3, 4]:
print >>sys.stderr, __doc__
sys.exit()
-
+
if len(sys.argv) == 3:
layer = 1
else:
@@ -764,7 +854,7 @@
sys.exit()
app = wx.App(0)
- sqlb = sqlBuilder(parent = None, vectmap = sys.argv[2], layer = layer)
+ sqlb = sqlBuilder(parent=None, vectmap=sys.argv[2], layer=layer)
sqlb.Show()
-
+
app.MainLoop()
Modified: grass/trunk/gui/wxpython/dbmgr/vinfo.py
===================================================================
--- grass/trunk/gui/wxpython/dbmgr/vinfo.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/dbmgr/vinfo.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,11 +20,12 @@
import wx
from gui_core.gselect import VectorDBInfo as VectorDBInfoBase
-from core.gcmd import RunCommand, GError
-from core.settings import UserSettings
+from core.gcmd import RunCommand, GError
+from core.settings import UserSettings
from core.utils import _
import grass.script as grass
+
def GetUnicodeValue(value):
"""Get unicode value
@@ -32,57 +33,69 @@
:return: unicode value
"""
- if type(value) == types.UnicodeType:
+ if isinstance(value, types.UnicodeType):
return value
-
- enc = UserSettings.Get(group = 'atm', key = 'encoding', subkey = 'value')
+
+ enc = UserSettings.Get(group='atm', key='encoding', subkey='value')
if not enc and 'GRASS_DB_ENCODING' in os.environ:
enc = os.environ['GRASS_DB_ENCODING']
else:
- enc = 'utf-8' # assuming UTF-8
-
- return unicode(str(value), enc, errors = 'replace')
+ enc = 'utf-8' # assuming UTF-8
+ return unicode(str(value), enc, errors='replace')
+
+
def CreateDbInfoDesc(panel, mapDBInfo, layer):
"""Create database connection information content"""
- infoFlexSizer = wx.FlexGridSizer (cols = 2, hgap = 1, vgap = 1)
+ infoFlexSizer = wx.FlexGridSizer(cols=2, hgap=1, vgap=1)
infoFlexSizer.AddGrowableCol(1)
-
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = "Driver:"))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = mapDBInfo.layers[layer]['driver']))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = "Database:"))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = mapDBInfo.layers[layer]['database']))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = "Table:"))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = mapDBInfo.layers[layer]['table']))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = "Key:"))
- infoFlexSizer.Add(item = wx.StaticText(parent = panel, id = wx.ID_ANY,
- label = mapDBInfo.layers[layer]['key']))
-
+
+ infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label="Driver:"))
+ infoFlexSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=mapDBInfo.layers[layer]['driver']))
+ infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label="Database:"))
+ infoFlexSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=mapDBInfo.layers[layer]['database']))
+ infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label="Table:"))
+ infoFlexSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=mapDBInfo.layers[layer]['table']))
+ infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label="Key:"))
+ infoFlexSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY,
+ label=mapDBInfo.layers[layer]['key']))
+
return infoFlexSizer
-
+
+
class VectorDBInfo(VectorDBInfoBase):
"""Class providing information about attribute tables
linked to the vector map"""
+
def __init__(self, map):
VectorDBInfoBase.__init__(self, map)
-
+
def GetColumns(self, table):
"""Return list of columns names (based on their index)"""
try:
names = [''] * len(self.tables[table].keys())
except KeyError:
return []
-
+
for name, desc in self.tables[table].iteritems():
names[desc['index']] = name
-
+
return names
def SelectByPoint(self, queryCoords, qdist):
@@ -93,17 +106,21 @@
nselected = 0
try:
- data = grass.vector_what(map=self.map,
- coord=(float(queryCoords[0]), float(queryCoords[1])),
- distance=float(qdist))
+ data = grass.vector_what(
+ map=self.map, coord=(
+ float(
+ queryCoords[0]), float(
+ queryCoords[1])), distance=float(qdist))
except grass.ScriptError:
- GError(parent=None,
- message=_("Failed to query vector map <{map}>. "
- "Check database settings and topology.").format(map=self.map))
+ GError(
+ parent=None, message=_(
+ "Failed to query vector map <{map}>. "
+ "Check database settings and topology.").format(
+ map=self.map))
if len(data) < 1 or all(('Table' not in record) for record in data):
return None
-
+
# process attributes
ret = dict()
for key in ['Category', 'Layer', 'Table', 'Id']:
@@ -119,11 +136,11 @@
value = None
else:
if self.tables[table][key]['ctype'] != types.StringType:
- value = self.tables[table][key]['ctype'] (value)
+ value = self.tables[table][key]['ctype'](value)
else:
value = GetUnicodeValue(value)
self.tables[table][key]['values'].append(value)
-
+
for key, value in record.iteritems():
if key == 'Attributes':
continue
@@ -133,8 +150,8 @@
ret['Id'].append(None)
return ret
-
- def SelectFromTable(self, layer, cols = '*', where = None):
+
+ def SelectFromTable(self, layer, cols='*', where=None):
"""Select records from the table
Return number of selected records, -1 on error
@@ -144,29 +161,29 @@
nselected = 0
- table = self.layers[layer]["table"] # get table desc
+ table = self.layers[layer]["table"] # get table desc
# select values (only one record)
if where is None or where is '':
sql = "SELECT %s FROM %s" % (cols, table)
else:
sql = "SELECT %s FROM %s WHERE %s" % (cols, table, where)
-
+
ret = RunCommand('db.select',
- read = True,
- quiet = True,
- flags = 'v',
- sql= sql,
- database = self.layers[layer]["database"],
- driver = self.layers[layer]["driver"])
-
+ read=True,
+ quiet=True,
+ flags='v',
+ sql=sql,
+ database=self.layers[layer]["database"],
+ driver=self.layers[layer]["driver"])
+
# self.tables[table][key][1] = str(cat)
if ret:
for line in ret.splitlines():
name, value = line.split('|')
# casting ...
if value:
- if self.tables[table][name]['ctype'] != type(''):
- value = self.tables[table][name]['ctype'] (value)
+ if not isinstance('', self.tables[table][name]['ctype']):
+ value = self.tables[table][name]['ctype'](value)
else:
value = GetUnicodeValue(value)
else:
Modified: grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py
===================================================================
--- grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/docs/wxgui_sphinx/conf.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -12,7 +12,8 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
-import sys, os
+import sys
+import os
from datetime import date
import string
from shutil import copy
@@ -22,12 +23,19 @@
# documentation root, use os.path.abspath to make it absolute, like shown here.
if not os.getenv('GISBASE'):
sys.exit("GISBASE not defined")
-sys.path.insert(0, os.path.abspath(os.path.join(os.environ['GISBASE'], 'etc', 'python', 'grass')))
+sys.path.insert(
+ 0,
+ os.path.abspath(
+ os.path.join(
+ os.environ['GISBASE'],
+ 'etc',
+ 'python',
+ 'grass')))
from grass.script import core
-footer_tmpl = string.Template(\
-r"""
+footer_tmpl = string.Template(
+ r"""
{% block footer %}<hr class="header">
<p><a href="../index.html">Help Index</a> | <a href="../topics.html">Topics Index</a> | <a href="../keywords.html">Keywords Index</a> | <a href="../full_index.html">Full Index</a></p>
<p>© 2003-${year} <a href="http://grass.osgeo.org">GRASS Development Team</a>, GRASS GIS ${grass_version} Reference Manual</p>
@@ -39,10 +47,13 @@
copy("_templates/layout.html.template", "_templates/layout.html")
with open("_templates/layout.html", "a+b") as f:
- f.write(footer_tmpl.substitute(grass_version=grass_version, year=today.year))
+ f.write(
+ footer_tmpl.substitute(
+ grass_version=grass_version,
+ year=today.year))
f.close()
-# -- General configuration -----------------------------------------------------
+# -- General configuration -----------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
@@ -174,7 +185,7 @@
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
-html_sidebars = {"**":["localtoc.html",'relations.html','searchbox.html']}
+html_sidebars = {"**": ["localtoc.html", 'relations.html', 'searchbox.html']}
# Additional templates that should be rendered to pages, maps page names to
# template names.
@@ -213,22 +224,22 @@
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
-# The paper size ('letterpaper' or 'a4paper').
-'papersize': 'a4paper',
+ # The paper size ('letterpaper' or 'a4paper').
+ 'papersize': 'a4paper',
-# The font size ('10pt', '11pt' or '12pt').
-'pointsize': '10pt',
+ # The font size ('10pt', '11pt' or '12pt').
+ 'pointsize': '10pt',
-# Additional stuff for the LaTeX preamble.
-#'preamble': '',
+ # Additional stuff for the LaTeX preamble.
+ #'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
- ('index', 'wxGUI.tex', u'wxGUI Documentation',
- u'GRASS Development Team', 'manual'),
+ ('index', 'wxGUI.tex', u'wxGUI Documentation',
+ u'GRASS Development Team', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -271,9 +282,9 @@
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- ('index', 'wxGUI', u'wxGUI Documentation',
- u'GRASS Development Team', 'wxGUI', 'One line description of project.',
- 'Miscellaneous'),
+ ('index', 'wxGUI', u'wxGUI Documentation',
+ u'GRASS Development Team', 'wxGUI', 'One line description of project.',
+ 'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
Modified: grass/trunk/gui/wxpython/gcp/__init__.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/__init__.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/__init__.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -2,4 +2,4 @@
'manager',
'mapdisplay',
'toolbars',
- ]
+]
Modified: grass/trunk/gui/wxpython/gcp/g.gui.gcp.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/g.gui.gcp.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/g.gui.gcp.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -47,10 +47,10 @@
options, flags = gscript.parser()
import wx
-
+
from grass.script.setup import set_gui_path
set_gui_path()
-
+
from core.settings import UserSettings
from core.globalvar import CheckWxVersion
from core.giface import StandaloneGrassInterface
Modified: grass/trunk/gui/wxpython/gcp/manager.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/manager.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/manager.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -35,22 +35,22 @@
import wx
from wx.lib.mixins.listctrl import CheckListCtrlMixin, ColumnSorterMixin, ListCtrlAutoWidthMixin
import wx.lib.colourselect as csel
-import wx.wizard as wiz
+import wx.wizard as wiz
import grass.script as grass
-from core import globalvar
-from core import utils
-from core.render import Map
+from core import globalvar
+from core import utils
+from core.render import Map
from core.utils import _
-from gui_core.gselect import Select, LocationSelect, MapsetSelect
-from gui_core.dialogs import GroupDialog
-from core.gcmd import RunCommand, GMessage, GError, GWarning, EncodeString
-from core.settings import UserSettings
-from gcp.mapdisplay import MapFrame
+from gui_core.gselect import Select, LocationSelect, MapsetSelect
+from gui_core.dialogs import GroupDialog
+from core.gcmd import RunCommand, GMessage, GError, GWarning, EncodeString
+from core.settings import UserSettings
+from gcp.mapdisplay import MapFrame
from core.giface import Notification
-from location_wizard.wizard import TitledPage as TitledPage
+from location_wizard.wizard import TitledPage as TitledPage
#
# global variables
@@ -60,10 +60,11 @@
global maptype
src_map = ''
-tgt_map = { 'raster' : '',
- 'vector' : '' }
+tgt_map = {'raster': '',
+ 'vector': ''}
maptype = 'raster'
+
def getSmallUpArrowImage():
stream = open(os.path.join(globalvar.IMGDIR, 'small_up_arrow.png'), 'rb')
try:
@@ -72,6 +73,7 @@
stream.close()
return img
+
def getSmallDnArrowImage():
stream = open(os.path.join(globalvar.IMGDIR, 'small_down_arrow.png'), 'rb')
try:
@@ -81,20 +83,21 @@
stream.close()
return img
+
class GCPWizard(object):
"""
Start wizard here and finish wizard here
"""
def __init__(self, parent, giface):
- self.parent = parent # GMFrame
+ self.parent = parent # GMFrame
self._giface = giface
#
# get environmental variables
#
self.grassdatabase = grass.gisenv()['GISDBASE']
-
+
#
# read original environment settings
#
@@ -110,13 +113,13 @@
self.gisrc_dict[key.strip()] = value.strip()
finally:
f.close()
-
+
self.currentlocation = self.gisrc_dict['LOCATION_NAME']
self.currentmapset = self.gisrc_dict['MAPSET']
# location for xy map to georectify
self.newlocation = ''
# mapset for xy map to georectify
- self.newmapset = ''
+ self.newmapset = ''
global maptype
global src_map
@@ -133,7 +136,10 @@
#
# define wizard pages
#
- self.wizard = wiz.Wizard(parent=parent, id=wx.ID_ANY, title=_("Setup for georectification"))
+ self.wizard = wiz.Wizard(
+ parent=parent,
+ id=wx.ID_ANY,
+ title=_("Setup for georectification"))
self.startpage = LocationPage(self.wizard, self)
self.grouppage = GroupPage(self.wizard, self)
self.mappage = DispMapPage(self.wizard, self)
@@ -165,12 +171,12 @@
if self.wizard.RunWizard(self.startpage):
success = self.OnWizFinished()
if success == False:
- GMessage(parent = self.parent,
- message = _("Georectifying setup canceled."))
+ GMessage(parent=self.parent,
+ message=_("Georectifying setup canceled."))
self.Cleanup()
else:
- GMessage(parent = self.parent,
- message = _("Georectifying setup canceled."))
+ GMessage(parent=self.parent,
+ message=_("Georectifying setup canceled."))
self.Cleanup()
#
@@ -179,25 +185,31 @@
if success != False:
# instance of render.Map to be associated with display
self.SwitchEnv('source')
- self.SrcMap = Map(gisrc=self.source_gisrc)
+ self.SrcMap = Map(gisrc=self.source_gisrc)
self.SwitchEnv('target')
self.TgtMap = Map(gisrc=self.target_gisrc)
self.Map = self.SrcMap
-
+
#
# add layer to source map
#
if maptype == 'raster':
rendertype = 'raster'
cmdlist = ['d.rast', 'map=%s' % src_map]
- else: # -> vector layer
+ else: # -> vector layer
rendertype = 'vector'
cmdlist = ['d.vect', 'map=%s' % src_map]
-
+
self.SwitchEnv('source')
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.SrcMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
+ self.SrcMap.AddLayer(
+ ltype=rendertype,
+ command=cmdlist,
+ active=True,
+ name=name,
+ hidden=False,
+ opacity=1.0,
+ render=False)
self.SwitchEnv('target')
if tgt_map['raster']:
@@ -206,26 +218,38 @@
#
rendertype = 'raster'
cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
-
+
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.TgtMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
-
+ self.TgtMap.AddLayer(
+ ltype=rendertype,
+ command=cmdlist,
+ active=True,
+ name=name,
+ hidden=False,
+ opacity=1.0,
+ render=False)
+
if tgt_map['vector']:
#
# add raster layer to target map
#
rendertype = 'vector'
cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
-
+
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.TgtMap.AddLayer(ltype=rendertype, command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
-
+ self.TgtMap.AddLayer(
+ ltype=rendertype,
+ command=cmdlist,
+ active=True,
+ name=name,
+ hidden=False,
+ opacity=1.0,
+ render=False)
+
#
# start GCP Manager
#
- self.gcpmgr = GCP(self.parent, giface = self._giface,
+ self.gcpmgr = GCP(self.parent, giface=self._giface,
grwiz=self, size=globalvar.MAP_WINDOW_SIZE,
toolbars=["gcpdisp"],
Map=self.SrcMap, lmgr=self.parent)
@@ -238,7 +262,7 @@
self.gcpmgr._mgr.Update()
else:
self.Cleanup()
-
+
def SetSrcEnv(self, location, mapset):
"""Create environment to use for location and mapset
that are the source of the file(s) to georectify
@@ -249,21 +273,22 @@
:return: False on error
:return: True on success
"""
-
+
self.newlocation = location
self.newmapset = mapset
-
- # check to see if we are georectifying map in current working location/mapset
+
+ # check to see if we are georectifying map in current working
+ # location/mapset
if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
return False
-
+
self.gisrc_dict['LOCATION_NAME'] = location
self.gisrc_dict['MAPSET'] = mapset
-
+
self.source_gisrc = EncodeString(utils.GetTempfile())
try:
- f = open(self.source_gisrc, mode='w')
+ f = open(self.source_gisrc, mode='w')
for line in self.gisrc_dict.items():
f.write(line[0] + ": " + line[1] + "\n")
finally:
@@ -276,7 +301,8 @@
Switches between original working location/mapset and
location/mapset that is source of file(s) to georectify
"""
- # check to see if we are georectifying map in current working location/mapset
+ # check to see if we are georectifying map in current working
+ # location/mapset
if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
return False
@@ -286,16 +312,16 @@
os.environ['GISRC'] = str(self.source_gisrc)
return True
-
+
def OnWizFinished(self):
# self.Cleanup()
return True
-
+
def OnGLMFocus(self, event):
"""Layer Manager focus"""
# self.SwitchEnv('target')
-
+
event.Skip()
def Cleanup(self):
@@ -306,50 +332,71 @@
self.SwitchEnv('target')
self.wizard.Destroy()
+
class LocationPage(TitledPage):
"""
Set map type (raster or vector) to georectify and
select location/mapset of map(s) to georectify.
"""
+
def __init__(self, wizard, parent):
- TitledPage.__init__(self, wizard, _("Select map type and location/mapset"))
+ TitledPage.__init__(self, wizard, _(
+ "Select map type and location/mapset"))
self.parent = parent
self.grassdatabase = self.parent.grassdatabase
-
+
self.xylocation = ''
self.xymapset = ''
-
+
#
# layout
#
# map type
- self.rb_maptype = wx.RadioBox(parent=self, id=wx.ID_ANY,
- label=' %s ' % _("Map type to georectify"),
- choices=[_('raster'), _('vector')],
- majorDimension=wx.RA_SPECIFY_COLS)
+ self.rb_maptype = wx.RadioBox(
+ parent=self, id=wx.ID_ANY, label=' %s ' %
+ _("Map type to georectify"), choices=[
+ _('raster'), _('vector')], majorDimension=wx.RA_SPECIFY_COLS)
self.sizer.Add(item=self.rb_maptype,
flag=wx.ALIGN_CENTER | wx.ALL | wx.EXPAND, border=5,
pos=(1, 1), span=(1, 2))
# location
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source location:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 1))
- self.cb_location = LocationSelect(parent = self, gisdbase = self.grassdatabase)
- self.sizer.Add(item=self.cb_location,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 2))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select source location:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 1))
+ self.cb_location = LocationSelect(
+ parent=self, gisdbase=self.grassdatabase)
+ self.sizer.Add(
+ item=self.cb_location,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 2))
# mapset
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source mapset:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3, 1))
- self.cb_mapset = MapsetSelect(parent = self, gisdbase = self.grassdatabase,
- setItems = False)
- self.sizer.Add(item=self.cb_mapset,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3,2))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select source mapset:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 3,
+ 1))
+ self.cb_mapset = MapsetSelect(parent=self, gisdbase=self.grassdatabase,
+ setItems=False)
+ self.sizer.Add(item=self.cb_mapset, flag=wx.ALIGN_LEFT |
+ wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
self.sizer.AddGrowableCol(2)
#
@@ -362,7 +409,7 @@
self.Bind(wiz.EVT_WIZARD_PAGE_CHANGED, self.OnEnterPage)
# self.Bind(wx.EVT_CLOSE, self.parent.Cleanup)
- def OnMaptype(self,event):
+ def OnMaptype(self, event):
"""Change map type"""
global maptype
@@ -370,17 +417,17 @@
maptype = 'raster'
else:
maptype = 'vector'
-
+
def OnLocation(self, event):
"""Sets source location for map(s) to georectify"""
self.xylocation = event.GetString()
-
- #create a list of valid mapsets
+
+ # create a list of valid mapsets
tmplist = os.listdir(os.path.join(self.grassdatabase, self.xylocation))
self.mapsetList = []
for item in tmplist:
if os.path.isdir(os.path.join(self.grassdatabase, self.xylocation, item)) and \
- os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
+ os.path.exists(os.path.join(self.grassdatabase, self.xylocation, item, 'WIND')):
if item != 'PERMANENT':
self.mapsetList.append(item)
@@ -389,7 +436,7 @@
self.mapsetList.insert(0, 'PERMANENT')
self.cb_mapset.SetItems(self.mapsetList)
self.cb_mapset.SetStringSelection(self.xymapset)
-
+
if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
@@ -398,43 +445,46 @@
if self.xylocation == '':
GMessage(_('You must select a valid location '
'before selecting a mapset'),
- parent = self)
+ parent=self)
return
self.xymapset = event.GetString()
-
+
if not wx.FindWindowById(wx.ID_FORWARD).IsEnabled():
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
def OnPageChanging(self, event=None):
if event.GetDirection() and \
- (self.xylocation == '' or self.xymapset == ''):
+ (self.xylocation == '' or self.xymapset == ''):
GMessage(_('You must select a valid location '
- 'and mapset in order to continue'),
- parent = self)
+ 'and mapset in order to continue'),
+ parent=self)
event.Veto()
return
-
+
self.parent.SetSrcEnv(self.xylocation, self.xymapset)
-
+
def OnEnterPage(self, event=None):
if self.xylocation == '' or self.xymapset == '':
wx.FindWindowById(wx.ID_FORWARD).Enable(False)
else:
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
+
class GroupPage(TitledPage):
"""
Set group to georectify. Create group if desired.
"""
+
def __init__(self, wizard, parent):
- TitledPage.__init__(self, wizard, _("Select image/map group to georectify"))
+ TitledPage.__init__(self, wizard, _(
+ "Select image/map group to georectify"))
self.parent = parent
-
+
self.grassdatabase = self.parent.grassdatabase
self.groupList = []
-
+
self.xylocation = ''
self.xymapset = ''
self.xygroup = ''
@@ -446,42 +496,73 @@
# layout
#
# group
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select group:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(1, 1))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select group:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 1,
+ 1))
self.cb_group = wx.ComboBox(parent=self, id=wx.ID_ANY,
choices=self.groupList, size=(350, -1),
style=wx.CB_DROPDOWN | wx.CB_READONLY)
- self.sizer.Add(item=self.cb_group,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(1, 2))
-
- # create group
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Create group if none exists')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 1))
+ self.sizer.Add(item=self.cb_group, flag=wx.ALIGN_LEFT |
+ wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(1, 2))
+
+ # create group
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Create group if none exists')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 1))
btnSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.btn_mkgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Create/edit group..."))
- self.btn_vgroup = wx.Button(parent=self, id=wx.ID_ANY, label=_("Add vector map to group..."))
+ self.btn_mkgroup = wx.Button(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_("Create/edit group..."))
+ self.btn_vgroup = wx.Button(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_("Add vector map to group..."))
btnSizer.Add(item=self.btn_mkgroup,
flag=wx.RIGHT, border=5)
btnSizer.Add(item=self.btn_vgroup,
flag=wx.LEFT, border=5)
-
- self.sizer.Add(item=btnSizer,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 2))
-
+
+ self.sizer.Add(
+ item=btnSizer,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 2))
+
# extension
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Extension for output maps:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3, 1))
- self.ext_txt = wx.TextCtrl(parent=self, id=wx.ID_ANY, value="", size=(350,-1))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Extension for output maps:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 3,
+ 1))
+ self.ext_txt = wx.TextCtrl(
+ parent=self, id=wx.ID_ANY, value="", size=(
+ 350, -1))
self.ext_txt.SetValue(self.extension)
- self.sizer.Add(item=self.ext_txt,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3, 2))
+ self.sizer.Add(item=self.ext_txt, flag=wx.ALIGN_LEFT |
+ wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5, pos=(3, 2))
self.sizer.AddGrowableCol(2)
#
@@ -496,12 +577,12 @@
# hide vector group button by default
self.btn_vgroup.Hide()
- def OnGroup(self, event):
+ def OnGroup(self, event):
self.xygroup = event.GetString()
-
+
def OnMkGroup(self, event):
"""Create new group in source location/mapset"""
- dlg = GroupDialog(parent = self, defaultGroup = self.xygroup)
+ dlg = GroupDialog(parent=self, defaultGroup=self.xygroup)
dlg.DisableSubgroupEdit()
dlg.ShowModal()
gr, s = dlg.GetSelectedGroup()
@@ -510,25 +591,25 @@
else:
gr = ''
dlg.Destroy()
-
+
self.OnEnterPage()
self.Update()
-
+
def OnVGroup(self, event):
"""Add vector maps to group"""
- dlg = VectGroup(parent = self,
- id = wx.ID_ANY,
- grassdb = self.grassdatabase,
- location = self.xylocation,
- mapset = self.xymapset,
- group = self.xygroup)
+ dlg = VectGroup(parent=self,
+ id=wx.ID_ANY,
+ grassdb=self.grassdatabase,
+ location=self.xylocation,
+ mapset=self.xymapset,
+ group=self.xygroup)
if dlg.ShowModal() != wx.ID_OK:
return
dlg.MakeVGroup()
self.OnEnterPage()
-
+
def OnExtension(self, event):
self.extension = self.ext_txt.GetValue()
@@ -536,20 +617,20 @@
if event.GetDirection() and self.xygroup == '':
GMessage(_('You must select a valid image/map '
'group in order to continue'),
- parent = self)
+ parent=self)
event.Veto()
return
if event.GetDirection() and self.extension == '':
GMessage(_('You must enter an map name '
'extension in order to continue'),
- parent = self)
+ parent=self)
event.Veto()
return
def OnEnterPage(self, event=None):
global maptype
-
+
self.groupList = []
self.xylocation = self.parent.gisrc_dict['LOCATION_NAME']
@@ -571,7 +652,7 @@
'group',
item)):
self.groupList.append(item)
-
+
if maptype == 'raster':
self.btn_vgroup.Hide()
self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
@@ -580,34 +661,37 @@
self.btn_vgroup.Show()
self.Bind(wx.EVT_BUTTON, self.OnMkGroup, self.btn_mkgroup)
self.Bind(wx.EVT_BUTTON, self.OnVGroup, self.btn_vgroup)
-
+
utils.ListSortLower(self.groupList)
self.cb_group.SetItems(self.groupList)
-
+
if len(self.groupList) > 0:
if self.xygroup and self.xygroup in self.groupList:
self.cb_group.SetStringSelection(self.xygroup)
else:
self.cb_group.SetSelection(0)
self.xygroup = self.groupList[0]
-
+
if self.xygroup == '' or \
self.extension == '':
wx.FindWindowById(wx.ID_FORWARD).Enable(False)
else:
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
-
+
# switch to source
self.parent.SwitchEnv('source')
-
+
+
class DispMapPage(TitledPage):
"""
Select ungeoreferenced map to display for interactively
setting ground control points (GCPs).
"""
+
def __init__(self, wizard, parent):
- TitledPage.__init__(self, wizard,
- _("Select maps to display for ground control point (GCP) creation"))
+ TitledPage.__init__(
+ self, wizard,
+ _("Select maps to display for ground control point (GCP) creation"))
self.parent = parent
global maptype
@@ -615,39 +699,78 @@
#
# layout
#
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select source map to display:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(1, 1))
-
- self.srcselection = Select(self, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type=maptype, updateOnPopup = False)
-
- self.sizer.Add(item=self.srcselection,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(1, 2))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select source map to display:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 1,
+ 1))
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select target raster map to display:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 1))
+ self.srcselection = Select(
+ self,
+ id=wx.ID_ANY,
+ size=globalvar.DIALOG_GSELECT_SIZE,
+ type=maptype,
+ updateOnPopup=False)
- self.tgtrastselection = Select(self, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type='raster', updateOnPopup = False)
+ self.sizer.Add(
+ item=self.srcselection,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 1,
+ 2))
- self.sizer.Add(item=self.tgtrastselection,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(2, 2))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select target raster map to display:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 1))
- self.sizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY, label=_('Select target vector map to display:')),
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3, 1))
+ self.tgtrastselection = Select(
+ self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+ type='raster', updateOnPopup=False)
- self.tgtvectselection = Select(self, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type='vector', updateOnPopup = False)
-
- self.sizer.Add(item=self.tgtvectselection,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5,
- pos=(3, 2))
+ self.sizer.Add(
+ item=self.tgtrastselection,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 2,
+ 2))
+ self.sizer.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select target vector map to display:')),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 3,
+ 1))
+
+ self.tgtvectselection = Select(
+ self, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+ type='vector', updateOnPopup=False)
+
+ self.sizer.Add(
+ item=self.tgtvectselection,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5,
+ pos=(
+ 3,
+ 2))
+
#
# bindings
#
@@ -671,12 +794,13 @@
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
try:
- # set computational region to match selected map and zoom display to region
+ # set computational region to match selected map and zoom display
+ # to region
if maptype == 'raster':
p = RunCommand('g.region', 'raster=src_map')
elif maptype == 'vector':
p = RunCommand('g.region', 'vector=src_map')
-
+
if p.returncode == 0:
print 'returncode = ', str(p.returncode)
self.parent.Map.region = self.parent.Map.GetRegion()
@@ -689,7 +813,7 @@
tgt_map['raster'] = self.tgtrastselection.GetValue()
- def OnTgtVectSelection(self,event):
+ def OnTgtVectSelection(self, event):
"""Source map to display selected"""
global tgt_map
@@ -702,12 +826,12 @@
if event.GetDirection() and (src_map == ''):
GMessage(_('You must select a source map '
'in order to continue'),
- parent = self)
+ parent=self)
event.Veto()
return
self.parent.SwitchEnv('target')
-
+
def OnEnterPage(self, event=None):
global maptype
global src_map
@@ -717,18 +841,19 @@
if maptype == 'raster':
ret = RunCommand('i.group',
- parent = self,
- read = True,
- group = self.parent.grouppage.xygroup,
- flags = 'g')
+ parent=self,
+ read=True,
+ group=self.parent.grouppage.xygroup,
+ flags='g')
if ret:
self.parent.src_maps = ret.splitlines()
else:
- GError(parent = self,
- message = _('No maps in selected group <%s>.\n'
- 'Please edit group or select another group.') %
- self.parent.grouppage.xygroup)
+ GError(
+ parent=self, message=_(
+ 'No maps in selected group <%s>.\n'
+ 'Please edit group or select another group.') %
+ self.parent.grouppage.xygroup)
return
elif maptype == 'vector':
@@ -738,11 +863,11 @@
# make list of vectors to georectify from VREF
vgrpfile = os.path.join(grassdatabase,
- xylocation,
- xymapset,
- 'group',
- self.parent.grouppage.xygroup,
- 'VREF')
+ xylocation,
+ xymapset,
+ 'group',
+ self.parent.grouppage.xygroup,
+ 'VREF')
f = open(vgrpfile)
try:
@@ -753,16 +878,17 @@
self.parent.src_maps.append(vect)
finally:
f.close()
-
+
if len(self.parent.src_maps) < 1:
- GError(parent = self,
- message = _('No maps in selected group <%s>.\n'
- 'Please edit group or select another group.') %
- self.parent.grouppage.xygroup)
+ GError(
+ parent=self, message=_(
+ 'No maps in selected group <%s>.\n'
+ 'Please edit group or select another group.') %
+ self.parent.grouppage.xygroup)
return
# filter out all maps not in group
- self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
+ self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
src_map = self.parent.src_maps[0]
self.srcselection.SetValue(src_map)
@@ -778,26 +904,35 @@
else:
wx.FindWindowById(wx.ID_FORWARD).Enable(True)
+
class GCP(MapFrame, ColumnSorterMixin):
"""
Manages ground control points for georectifying. Calculates RMS statistics.
Calls i.rectify or v.rectify to georectify map.
"""
- def __init__(self, parent, giface, grwiz = None, id = wx.ID_ANY,
- title = _("Manage Ground Control Points"),
- size = (700, 300), toolbars = ["gcpdisp"], Map = None, lmgr = None):
- self.grwiz = grwiz # GR Wizard
+ def __init__(self, parent, giface, grwiz=None, id=wx.ID_ANY,
+ title=_("Manage Ground Control Points"),
+ size=(700, 300), toolbars=["gcpdisp"], Map=None, lmgr=None):
+
+ self.grwiz = grwiz # GR Wizard
self._giface = giface
if tgt_map['raster'] == '' and tgt_map['vector'] == '':
self.show_target = False
else:
self.show_target = True
-
+
#wx.Frame.__init__(self, parent, id, title, size = size, name = "GCPFrame")
- MapFrame.__init__(self, parent = parent, giface = self._giface, title = title, size = size,
- Map=Map, toolbars=toolbars, name='GCPMapWindow')
+ MapFrame.__init__(
+ self,
+ parent=parent,
+ giface=self._giface,
+ title=title,
+ size=size,
+ Map=Map,
+ toolbars=toolbars,
+ name='GCPMapWindow')
# init variables
self.parent = parent
@@ -805,8 +940,10 @@
#
# register data structures for drawing GCP's
#
- self.pointsToDrawTgt = self.TgtMapWindow.RegisterGraphicsToDraw(graphicsType = "point", setStatusFunc = self.SetGCPSatus)
- self.pointsToDrawSrc = self.SrcMapWindow.RegisterGraphicsToDraw(graphicsType = "point", setStatusFunc = self.SetGCPSatus)
+ self.pointsToDrawTgt = self.TgtMapWindow.RegisterGraphicsToDraw(
+ graphicsType="point", setStatusFunc=self.SetGCPSatus)
+ self.pointsToDrawSrc = self.SrcMapWindow.RegisterGraphicsToDraw(
+ graphicsType="point", setStatusFunc=self.SetGCPSatus)
# connect to the map windows signals
# used to add or edit GCP
@@ -837,44 +974,44 @@
self.VectGRList = []
self.file = {
- 'points' : os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'group',
- self.xygroup,
- 'POINTS'),
- 'points_bak' : os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'group',
- self.xygroup,
- 'POINTS_BAK'),
- 'rgrp' : os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'group',
- self.xygroup,
- 'REF'),
- 'vgrp' : os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'group',
- self.xygroup,
- 'VREF'),
- 'target' : os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'group',
- self.xygroup,
- 'TARGET'),
- }
+ 'points': os.path.join(self.grassdatabase,
+ self.xylocation,
+ self.xymapset,
+ 'group',
+ self.xygroup,
+ 'POINTS'),
+ 'points_bak': os.path.join(self.grassdatabase,
+ self.xylocation,
+ self.xymapset,
+ 'group',
+ self.xygroup,
+ 'POINTS_BAK'),
+ 'rgrp': os.path.join(self.grassdatabase,
+ self.xylocation,
+ self.xymapset,
+ 'group',
+ self.xygroup,
+ 'REF'),
+ 'vgrp': os.path.join(self.grassdatabase,
+ self.xylocation,
+ self.xymapset,
+ 'group',
+ self.xygroup,
+ 'VREF'),
+ 'target': os.path.join(self.grassdatabase,
+ self.xylocation,
+ self.xymapset,
+ 'group',
+ self.xygroup,
+ 'TARGET'),
+ }
# make a backup of the current points file
if os.path.exists(self.file['points']):
shutil.copy(self.file['points'], self.file['points_bak'])
# polynomial order transformation for georectification
- self.gr_order = 1
+ self.gr_order = 1
# interpolation method for georectification
self.gr_method = 'nearest'
# region clipping for georectified map
@@ -887,17 +1024,17 @@
self.bkw_rmserror = 0.0
# list map coords and ID of map display they came from
self.mapcoordlist = []
- self.mapcoordlist.append([ 0, # GCP number
- 0.0, # source east
- 0.0, # source north
- 0.0, # target east
- 0.0, # target north
- 0.0, # forward error
- 0.0 ] ) # backward error
+ self.mapcoordlist.append([0, # GCP number
+ 0.0, # source east
+ 0.0, # source north
+ 0.0, # target east
+ 0.0, # target north
+ 0.0, # forward error
+ 0.0]) # backward error
# init vars to highlight high RMS errors
self.highest_only = True
- self.show_unused = True
+ self.show_unused = True
self.highest_key = -1
self.rmsthresh = 0
self.rmsmean = 0
@@ -911,8 +1048,8 @@
# CheckListCtrlMixin must set an ImageList first
self.il = self.list.GetImageList(wx.IMAGE_LIST_SMALL)
- SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())
- SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())
+ SmallUpArrow = wx.BitmapFromImage(getSmallUpArrowImage())
+ SmallDnArrow = wx.BitmapFromImage(getSmallDnArrowImage())
self.sm_dn = self.il.Add(SmallDnArrow)
self.sm_up = self.il.Add(SmallUpArrow)
@@ -925,7 +1062,7 @@
self.mapwin.SetNamedCursor('cross')
self.mapwin = self.TgtMapWindow
-
+
# set mouse characteristics
self.mapwin.mouse['box'] = 'point'
self.mapwin.mouse["use"] == "pointer"
@@ -949,10 +1086,10 @@
# bindings
#
self.Bind(wx.EVT_ACTIVATE, self.OnFocus)
- self.Bind(wx.EVT_SIZE, self.OnSize)
- self.Bind(wx.EVT_IDLE, self.OnIdle)
- self.Bind(wx.EVT_CLOSE, self.OnQuit)
-
+ self.Bind(wx.EVT_SIZE, self.OnSize)
+ self.Bind(wx.EVT_IDLE, self.OnIdle)
+ self.Bind(wx.EVT_CLOSE, self.OnQuit)
+
self.SetSettings()
def __del__(self):
@@ -960,7 +1097,7 @@
# leaving the method here but was used only to delete gcpmanagement
# from layer manager which is now not needed
pass
-
+
def CreateGCPList(self):
"""Create GCP List Control"""
@@ -969,7 +1106,7 @@
# Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
def GetListCtrl(self):
return self.list
-
+
def GetMapCoordList(self):
return self.mapcoordlist
@@ -979,13 +1116,13 @@
def GetFwdError(self):
return self.fwd_rmserror
-
+
def GetBkwError(self):
return self.bkw_rmserror
-
+
def InitMapDisplay(self):
self.list.LoadData()
-
+
# initialize column sorter
self.itemDataMap = self.mapcoordlist
ncols = self.list.GetColumnCount()
@@ -997,19 +1134,20 @@
"""
Sets rectification target to current location and mapset
"""
- # check to see if we are georectifying map in current working location/mapset
+ # check to see if we are georectifying map in current working
+ # location/mapset
if self.newlocation == self.currentlocation and self.newmapset == self.currentmapset:
RunCommand('i.target',
- parent = self,
- flags = 'c',
- group = tgroup)
+ parent=self,
+ flags='c',
+ group=tgroup)
else:
self.grwiz.SwitchEnv('source')
RunCommand('i.target',
- parent = self,
- group = tgroup,
- location = tlocation,
- mapset = tmapset)
+ parent=self,
+ group=tgroup,
+ location=tlocation,
+ mapset=tmapset)
self.grwiz.SwitchEnv('target')
def AddGCP(self, event):
@@ -1017,16 +1155,17 @@
Appends an item to GCP list
"""
keyval = self.list.AddGCPItem() + 1
- # source east, source north, target east, target north, forward error, backward error
- self.mapcoordlist.append([ keyval, # GCP number
- 0.0, # source east
- 0.0, # source north
- 0.0, # target east
- 0.0, # target north
- 0.0, # forward error
- 0.0 ] ) # backward error
+ # source east, source north, target east, target north, forward error,
+ # backward error
+ self.mapcoordlist.append([keyval, # GCP number
+ 0.0, # source east
+ 0.0, # source north
+ 0.0, # target east
+ 0.0, # target north
+ 0.0, # forward error
+ 0.0]) # backward error
- if self.statusbarManager.GetMode() == 8: # go to
+ if self.statusbarManager.GetMode() == 8: # go to
self.StatusbarUpdate()
def DeleteGCP(self, event):
@@ -1036,8 +1175,10 @@
minNumOfItems = self.OnGROrder(None)
if self.list.GetItemCount() <= minNumOfItems:
- GMessage(parent = self,
- message=_("At least %d GCPs required. Operation canceled.") % minNumOfItems)
+ GMessage(
+ parent=self,
+ message=_("At least %d GCPs required. Operation canceled.") %
+ minNumOfItems)
return
key = self.list.DeleteGCPItem()
@@ -1053,24 +1194,27 @@
# update selected
if self.list.GetItemCount() > 0:
if self.list.selected < self.list.GetItemCount():
- self.list.selectedkey = self.list.GetItemData(self.list.selected)
+ self.list.selectedkey = self.list.GetItemData(
+ self.list.selected)
else:
self.list.selected = self.list.GetItemCount() - 1
- self.list.selectedkey = self.list.GetItemData(self.list.selected)
-
+ self.list.selectedkey = self.list.GetItemData(
+ self.list.selected)
+
self.list.SetItemState(self.list.selected,
- wx.LIST_STATE_SELECTED,
- wx.LIST_STATE_SELECTED)
+ wx.LIST_STATE_SELECTED,
+ wx.LIST_STATE_SELECTED)
else:
self.list.selected = wx.NOT_FOUND
self.list.selectedkey = -1
self.UpdateColours()
- if self.statusbarManager.GetMode() == 8: # go to
+ if self.statusbarManager.GetMode() == 8: # go to
self.StatusbarUpdate()
if self.list.selectedkey > 0:
- self.statusbarManager.SetProperty('gotoGCP', self.list.selectedkey)
+ self.statusbarManager.SetProperty(
+ 'gotoGCP', self.list.selectedkey)
def ClearGCP(self, event):
"""
@@ -1085,56 +1229,63 @@
self.list.SetStringItem(index, 6, '')
self.list.CheckItem(index, False)
- # GCP number, source E, source N, target E, target N, fwd error, bkwd error
+ # GCP number, source E, source N, target E, target N, fwd error, bkwd
+ # error
self.mapcoordlist[key] = [key, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
def SetSettings(self):
"""Sets settings for drawing of GCP's.
"""
- self.highest_only = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
- self.show_unused = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
-
- colours = { "color" : "default",
- "hcolor" : "highest",
- "scolor" : "selected",
- "ucolor" : "unused" }
- wpx = UserSettings.Get(group = 'gcpman', key = 'symbol', subkey = 'width')
-
+ self.highest_only = UserSettings.Get(
+ group='gcpman', key='rms', subkey='highestonly')
+ self.show_unused = UserSettings.Get(
+ group='gcpman', key='symbol', subkey='unused')
+
+ colours = {"color": "default",
+ "hcolor": "highest",
+ "scolor": "selected",
+ "ucolor": "unused"}
+ wpx = UserSettings.Get(group='gcpman', key='symbol', subkey='width')
+
for k, v in colours.iteritems():
- col = UserSettings.Get(group='gcpman', key='symbol', subkey= k)
- self.pointsToDrawSrc.GetPen(v).SetColour(wx.Colour(col[0], col[1], col[2], 255)) # TODO GetPen neni to spatne?
- self.pointsToDrawTgt.GetPen(v).SetColour(wx.Colour(col[0], col[1], col[2], 255))
-
+ col = UserSettings.Get(group='gcpman', key='symbol', subkey=k)
+ self.pointsToDrawSrc.GetPen(v).SetColour(wx.Colour(
+ col[0], col[1], col[2], 255)) # TODO GetPen neni to spatne?
+ self.pointsToDrawTgt.GetPen(v).SetColour(
+ wx.Colour(col[0], col[1], col[2], 255))
+
self.pointsToDrawSrc.GetPen(v).SetWidth(wpx)
self.pointsToDrawTgt.GetPen(v).SetWidth(wpx)
-
- spx = UserSettings.Get(group = 'gcpman', key = 'symbol', subkey = 'size')
+
+ spx = UserSettings.Get(group='gcpman', key='symbol', subkey='size')
self.pointsToDrawSrc.SetPropertyVal("size", int(spx))
self.pointsToDrawTgt.SetPropertyVal("size", int(spx))
-
+
font = self.GetFont()
font.SetPointSize(int(spx) + 2)
-
+
textProp = {}
textProp['active'] = True
textProp['font'] = font
self.pointsToDrawSrc.SetPropertyVal("text", textProp)
self.pointsToDrawTgt.SetPropertyVal("text", copy(textProp))
-
+
def SetGCPSatus(self, item, itemIndex):
"""Before GCP is drawn, decides it's colour and whether it
will be drawed.
"""
key = self.list.GetItemData(itemIndex)
- itemIndex += 1 # incremented because of itemDataMap (has one more item) - will be changed
-
+ # incremented because of itemDataMap (has one more item) - will be
+ # changed
+ itemIndex += 1
+
if not self.list.IsChecked(key - 1):
- wxPen = "unused"
- if not self.show_unused:
- item.SetPropertyVal('hide', True)
- else:
- item.SetPropertyVal('hide', False)
-
+ wxPen = "unused"
+ if not self.show_unused:
+ item.SetPropertyVal('hide', True)
+ else:
+ item.SetPropertyVal('hide', False)
+
else:
item.SetPropertyVal('hide', False)
if self.highest_only == True:
@@ -1147,10 +1298,10 @@
wxPen = "highest"
else:
wxPen = "default"
-
+
if itemIndex == self.list.selectedkey:
wxPen = "selected"
-
+
item.SetPropertyVal('label', str(itemIndex))
item.SetPropertyVal('penName', wxPen)
@@ -1172,44 +1323,44 @@
currloc = _("source")
else:
currloc = _("target")
- ret = wx.MessageBox(parent = self,
- caption = _("Set GCP coordinates"),
- message = _('Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
- 'East: %(coor0)s \n'
- 'North: %(coor1)s') % \
- { 'coor' : currloc,
- 'key' : str(key),
- 'coor0' : str(coord0),
- 'coor1' : str(coord1) },
- style = wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
-
+ ret = wx.MessageBox(
+ parent=self, caption=_("Set GCP coordinates"),
+ message=_(
+ 'Set %(coor)s coordinates for GCP No. %(key)s? \n\n'
+ 'East: %(coor0)s \n'
+ 'North: %(coor1)s') %
+ {'coor': currloc, 'key': str(key),
+ 'coor0': str(coord0),
+ 'coor1': str(coord1)},
+ style=wx.ICON_QUESTION | wx.YES_NO | wx.CENTRE)
+
# for wingrass
if os.name == 'nt':
self.MapWindow.SetFocus()
if ret == wx.NO:
return
-
+
if coordtype == 'source':
self.list.SetStringItem(index, 1, str(coord0))
self.list.SetStringItem(index, 2, str(coord1))
self.mapcoordlist[key][1] = coord[0]
self.mapcoordlist[key][2] = coord[1]
self.pointsToDrawSrc.GetItem(key - 1).SetCoords([coord0, coord1])
-
+
elif coordtype == 'target':
self.list.SetStringItem(index, 3, str(coord0))
self.list.SetStringItem(index, 4, str(coord1))
self.mapcoordlist[key][3] = coord[0]
self.mapcoordlist[key][4] = coord[1]
self.pointsToDrawTgt.GetItem(key - 1).SetCoords([coord0, coord1])
-
+
self.list.SetStringItem(index, 5, '0')
self.list.SetStringItem(index, 6, '0')
self.mapcoordlist[key][5] = 0.0
self.mapcoordlist[key][6] = 0.0
-
+
# self.list.ResizeColumns()
-
+
def SaveGCPs(self, event):
"""Make a POINTS file or save GCP coordinates to existing
POINTS file
@@ -1224,7 +1375,8 @@
f.write("# target mapset: " + self.currentmapset + '\n')
f.write("#\tsource\t\ttarget\t\tstatus\n")
f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n")
- f.write("#----------------------- ----------------------- ---------------\n")
+ f.write(
+ "#----------------------- ----------------------- ---------------\n")
for index in range(self.list.GetItemCount()):
if self.list.IsChecked(index) == True:
@@ -1236,12 +1388,26 @@
coord1 = self.list.GetItem(index, 2).GetText()
coord2 = self.list.GetItem(index, 3).GetText()
coord3 = self.list.GetItem(index, 4).GetText()
- f.write(coord0 + ' ' + coord1 + ' ' + coord2 + ' ' + coord3 + ' ' + check + '\n')
+ f.write(
+ coord0 +
+ ' ' +
+ coord1 +
+ ' ' +
+ coord2 +
+ ' ' +
+ coord3 +
+ ' ' +
+ check +
+ '\n')
except IOError as err:
- GError(parent = self,
- message="%s <%s>. %s%s" % (_("Writing POINTS file failed"),
- self.file['points'], os.linesep, err))
+ GError(
+ parent=self,
+ message="%s <%s>. %s%s" %
+ (_("Writing POINTS file failed"),
+ self.file['points'],
+ os.linesep,
+ err))
return
f.close()
@@ -1249,41 +1415,43 @@
# if event != None save also to backup file
if event:
shutil.copy(self.file['points'], self.file['points_bak'])
- self._giface.WriteLog(_('POINTS file saved for group <%s>') % self.xygroup)
+ self._giface.WriteLog(
+ _('POINTS file saved for group <%s>') %
+ self.xygroup)
#self.SetStatusText(_('POINTS file saved'))
def ReadGCPs(self):
"""
Reads GCPs and georectified coordinates from POINTS file
"""
-
+
self.GCPcount = 0
sourceMapWin = self.SrcMapWindow
targetMapWin = self.TgtMapWindow
-
+
if not sourceMapWin:
- GError(parent = self,
- message = "%s. %s%s" % (_("source mapwin not defined"),
- os.linesep, err))
-
+ GError(parent=self,
+ message="%s. %s%s" % (_("source mapwin not defined"),
+ os.linesep, err))
+
if not targetMapWin:
- GError(parent = self,
+ GError(parent=self,
message="%s. %s%s" % (_("target mapwin not defined"),
os.linesep, err))
-
+
try:
f = open(self.file['points'], 'r')
GCPcnt = 0
-
+
for line in f.readlines():
- if line[0] == '#' or line =='':
+ if line[0] == '#' or line == '':
continue
line = line.replace('\n', '').strip()
coords = map(float, line.split())
if coords[4] == 1:
check = True
- self.GCPcount +=1
+ self.GCPcount += 1
else:
check = False
@@ -1296,9 +1464,13 @@
GCPcnt += 1
except IOError as err:
- GError(parent = self,
- message = "%s <%s>. %s%s" % (_("Reading POINTS file failed"),
- self.file['points'], os.linesep, err))
+ GError(
+ parent=self,
+ message="%s <%s>. %s%s" %
+ (_("Reading POINTS file failed"),
+ self.file['points'],
+ os.linesep,
+ err))
return
f.close()
@@ -1320,13 +1492,13 @@
# delete all items in mapcoordlist
self.mapcoordlist = []
- self.mapcoordlist.append([ 0, # GCP number
- 0.0, # source east
- 0.0, # source north
- 0.0, # target east
- 0.0, # target north
- 0.0, # forward error
- 0.0 ] ) # backward error
+ self.mapcoordlist.append([0, # GCP number
+ 0.0, # source east
+ 0.0, # source north
+ 0.0, # target east
+ 0.0, # target north
+ 0.0, # forward error
+ 0.0]) # backward error
self.list.LoadData()
self.itemDataMap = self.mapcoordlist
@@ -1341,7 +1513,7 @@
if self.show_target:
targetMapWin = self.TgtMapWindow
targetMapWin.UpdateMap(render=False, renderVector=False)
-
+
def OnFocus(self, event):
# TODO: it is here just to remove old or obsolate beavior of base class gcp/MapFrame?
# self.grwiz.SwitchEnv('source')
@@ -1361,29 +1533,31 @@
"""
RMS button handler
"""
- self.RMSError(self.xygroup,self.gr_order)
+ self.RMSError(self.xygroup, self.gr_order)
sourceMapWin = self.SrcMapWindow
sourceMapWin.UpdateMap(render=False, renderVector=False)
if self.show_target:
targetMapWin = self.TgtMapWindow
targetMapWin.UpdateMap(render=False, renderVector=False)
-
+
def CheckGCPcount(self, msg=False):
"""
Checks to make sure that the minimum number of GCPs have been defined and
are active for the selected transformation order
"""
if (self.GCPcount < 3 and self.gr_order == 1) or \
- (self.GCPcount < 6 and self.gr_order == 2) or \
- (self.GCPcount < 10 and self.gr_order == 3):
+ (self.GCPcount < 6 and self.gr_order == 2) or \
+ (self.GCPcount < 10 and self.gr_order == 3):
if msg:
- GWarning(parent = self,
- message=_('Insufficient points defined and active (checked) '
- 'for selected rectification method (order: %d).\n'
- '3+ points needed for 1st order,\n'
- '6+ points for 2nd order, and\n'
- '10+ points for 3rd order.') % self.gr_order)
+ GWarning(
+ parent=self, message=_(
+ 'Insufficient points defined and active (checked) '
+ 'for selected rectification method (order: %d).\n'
+ '3+ points needed for 1st order,\n'
+ '6+ points for 2nd order, and\n'
+ '10+ points for 3rd order.') %
+ self.gr_order)
return False
else:
return True
@@ -1394,7 +1568,7 @@
"""
global maptype
self.SaveGCPs(None)
-
+
if self.CheckGCPcount(msg=True) == False:
return
@@ -1411,26 +1585,26 @@
wx.Yield()
ret, msg = RunCommand('i.rectify',
- parent = self,
- getErrorMsg = True,
- quiet = True,
- group = self.xygroup,
- extension = self.extension,
- order = self.gr_order,
+ parent=self,
+ getErrorMsg=True,
+ quiet=True,
+ group=self.xygroup,
+ extension=self.extension,
+ order=self.gr_order,
method=self.gr_method,
- flags = flags)
+ flags=flags)
busy.Destroy()
# provide feedback on failure
if ret != 0:
print >> sys.stderr, msg
-
+
elif maptype == 'vector':
# loop through all vectors in VREF
self.grwiz.SwitchEnv('source')
-
+
# make list of vectors to georectify from VREF
f = open(self.file['vgrp'])
vectlist = []
@@ -1442,33 +1616,34 @@
vectlist.append(vect)
finally:
f.close()
-
+
# georectify each vector in VREF using v.rectify
for vect in vectlist:
self.outname = str(vect.split('@')[0]) + self.extension
- self._giface.WriteLog(text = _('Transforming <%s>...') % vect,
+ self._giface.WriteLog(text=_('Transforming <%s>...') % vect,
notification=Notification.MAKE_VISIBLE)
ret = msg = ''
-
- busy = wx.BusyInfo(message=_("Rectifying vector map <%s>, please wait...") % vect,
- parent=self)
+
+ busy = wx.BusyInfo(
+ message=_("Rectifying vector map <%s>, please wait...") %
+ vect, parent=self)
wx.Yield()
ret, msg = RunCommand('v.rectify',
- parent = self,
- getErrorMsg = True,
- quiet = True,
- input = vect,
- output = self.outname,
- group = self.xygroup,
- order = self.gr_order)
+ parent=self,
+ getErrorMsg=True,
+ quiet=True,
+ input=vect,
+ output=self.outname,
+ group=self.xygroup,
+ order=self.gr_order)
busy.Destroy()
# provide feedback on failure
if ret != 0:
print >> sys.stderr, msg
-
+
self.grwiz.SwitchEnv('target')
def OnGeorectDone(self, **kargs):
@@ -1476,17 +1651,17 @@
global maptype
if maptype == 'raster':
return
-
+
returncode = kargs['returncode']
-
+
if returncode == 0:
self.VectGRList.append(self.outname)
print '*****vector list = ' + str(self.VectGRList)
else:
- self._giface.WriteError(_('Georectification of vector map <%s> failed') %
- self.outname)
+ self._giface.WriteError(
+ _('Georectification of vector map <%s> failed') %
+ self.outname)
-
def OnSettings(self, event):
"""GCP Manager settings"""
dlg = GrSettingsDialog(parent=self, giface=self._giface,
@@ -1494,11 +1669,11 @@
if dlg.ShowModal() == wx.ID_OK:
pass
-
+
dlg.Destroy()
def UpdateColours(self, srcrender=False, srcrenderVector=False,
- tgtrender=False, tgtrenderVector=False):
+ tgtrender=False, tgtrenderVector=False):
"""update colours"""
highest_fwd_err = 0.0
self.highest_key = 0
@@ -1522,7 +1697,7 @@
self.list.SetItemTextColour(index, wx.BLACK)
else:
self.list.SetItemTextColour(index, wx.BLACK)
-
+
if self.highest_only and highest_fwd_err > 0.0:
self.list.SetItemTextColour(highest_idx, wx.RED)
@@ -1530,14 +1705,16 @@
sourceMapWin.UpdateMap(render=srcrender, renderVector=srcrenderVector)
if self.show_target:
targetMapWin = self.TgtMapWindow
- targetMapWin.UpdateMap(render=tgtrender, renderVector=tgtrenderVector)
+ targetMapWin.UpdateMap(
+ render=tgtrender,
+ renderVector=tgtrenderVector)
def OnQuit(self, event):
"""Quit georectifier"""
- ret = wx.MessageBox(parent=self,
- caption=_("Quit GCP Manager"),
- message=_('Save ground control points?'),
- style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
+ ret = wx.MessageBox(
+ parent=self, caption=_("Quit GCP Manager"),
+ message=_('Save ground control points?'),
+ style=wx.ICON_QUESTION | wx.YES_NO | wx.CANCEL | wx.CENTRE)
if ret != wx.CANCEL:
if ret == wx.YES:
@@ -1557,7 +1734,7 @@
self.Destroy()
- #event.Skip()
+ # event.Skip()
def OnGROrder(self, event):
"""
@@ -1568,7 +1745,7 @@
numOfItems = self.list.GetItemCount()
minNumOfItems = numOfItems
-
+
if self.gr_order == 1:
minNumOfItems = 3
# self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order'))
@@ -1586,7 +1763,7 @@
self.AddGCP(None)
return minNumOfItems
-
+
def RMSError(self, xygroup, order):
"""
Uses m.transform to calculate forward and backward error for each used GCP
@@ -1595,32 +1772,36 @@
"""
# save GCPs to points file to make sure that all checked GCPs are used
self.SaveGCPs(None)
- #self.SetStatusText('')
-
+ # self.SetStatusText('')
+
if self.CheckGCPcount(msg=True) == False:
return
-
+
# get list of forward and reverse rms error values for each point
self.grwiz.SwitchEnv('source')
-
+
ret = RunCommand('m.transform',
- parent = self,
- read = True,
- group = xygroup,
- order = order)
-
+ parent=self,
+ read=True,
+ group=xygroup,
+ order=order)
+
self.grwiz.SwitchEnv('target')
if ret:
errlist = ret.splitlines()
else:
- GError(parent = self,
+ GError(parent=self,
message=_('Could not calculate RMS Error.\n'
'Possible error with m.transform.'))
return
-
+
# insert error values into GCP list for checked items
- sdfactor = float(UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor'))
+ sdfactor = float(
+ UserSettings.Get(
+ group='gcpman',
+ key='rms',
+ subkey='sdfactor'))
GCPcount = 0
sumsq_fwd_err = 0.0
sumsq_bkw_err = 0.0
@@ -1628,7 +1809,7 @@
highest_fwd_err = 0.0
self.highest_key = 0
highest_idx = 0
-
+
for index in range(self.list.GetItemCount()):
key = self.list.GetItemData(index)
if self.list.IsChecked(index):
@@ -1643,7 +1824,7 @@
highest_fwd_err = float(fwd_err)
self.highest_key = key
highest_idx = index
-
+
sumsq_fwd_err += float(fwd_err)**2
sumsq_bkw_err += float(bkw_err)**2
sum_fwd_err += float(fwd_err)
@@ -1673,26 +1854,26 @@
key = self.list.GetItemData(index)
if (self.mapcoordlist[key][5] > self.rmsthresh):
self.list.SetItemTextColour(index, wx.RED)
-
+
# calculate global RMS error (geometric mean)
- self.fwd_rmserror = round((sumsq_fwd_err/GCPcount)**0.5,4)
- self.bkw_rmserror = round((sumsq_bkw_err/GCPcount)**0.5,4)
+ self.fwd_rmserror = round((sumsq_fwd_err / GCPcount)**0.5, 4)
+ self.bkw_rmserror = round((sumsq_bkw_err / GCPcount)**0.5, 4)
self.list.ResizeColumns()
- def GetNewExtent(self, region, map = None):
+ def GetNewExtent(self, region, map=None):
coord_file = utils.GetTempfile()
- newreg = { 'n' : 0.0, 's' : 0.0, 'e' : 0.0, 'w' : 0.0,}
+ newreg = {'n': 0.0, 's': 0.0, 'e': 0.0, 'w': 0.0, }
try:
f = open(coord_file, mode='w')
- # NW corner
+ # NW corner
f.write(str(region['e']) + " " + str(region['n']) + "\n")
- # NE corner
+ # NE corner
f.write(str(region['e']) + " " + str(region['s']) + "\n")
- # SW corner
+ # SW corner
f.write(str(region['w']) + " " + str(region['n']) + "\n")
- # SE corner
+ # SE corner
f.write(str(region['w']) + " " + str(region['s']) + "\n")
finally:
f.close()
@@ -1706,39 +1887,39 @@
if self.CheckGCPcount(msg=True) == False:
self.gr_order = order
return
-
+
self.gr_order = order
# get list of forward and reverse rms error values for each point
self.grwiz.SwitchEnv('source')
-
+
if map == 'source':
ret = RunCommand('m.transform',
- parent = self,
- read = True,
- group = self.xygroup,
- order = 1,
- format = 'dst',
- coords = coord_file)
+ parent=self,
+ read=True,
+ group=self.xygroup,
+ order=1,
+ format='dst',
+ coords=coord_file)
elif map == 'target':
ret = RunCommand('m.transform',
- parent = self,
- read = True,
- group = self.xygroup,
- order = 1,
- flags = 'r',
- format = 'src',
- coords = coord_file)
+ parent=self,
+ read=True,
+ group=self.xygroup,
+ order=1,
+ flags='r',
+ format='src',
+ coords=coord_file)
os.unlink(coord_file)
-
+
self.grwiz.SwitchEnv('target')
if ret:
errlist = ret.splitlines()
else:
- GError(parent = self,
+ GError(parent=self,
message=_('Could not calculate new extends.\n'
'Possible error with m.transform.'))
return
@@ -1788,7 +1969,8 @@
def UpdateActive(self, win):
# optionally disable tool zoomback tool
- self.GetMapToolbar().Enable('zoomback', enable = (len(self.MapWindow.zoomhistory) > 1))
+ self.GetMapToolbar().Enable('zoomback',
+ enable=(len(self.MapWindow.zoomhistory) > 1))
if self.activemap.GetSelection() != (win == self.TgtMapWindow):
self.activemap.SetSelection(win == self.TgtMapWindow)
@@ -1805,7 +1987,7 @@
self.Map.region['w'] = newreg['w']
self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
- self.Map.region['e'], self.Map.region['w'])
+ self.Map.region['e'], self.Map.region['w'])
# LL locations
if self.Map.projinfo['proj'] == 'll':
@@ -1813,19 +1995,20 @@
newreg['n'] = 90.0
if newreg['s'] < -90.0:
newreg['s'] = -90.0
-
+
ce = newreg['w'] + (newreg['e'] - newreg['w']) / 2
cn = newreg['s'] + (newreg['n'] - newreg['s']) / 2
-
+
# calculate new center point and display resolution
self.Map.region['center_easting'] = ce
self.Map.region['center_northing'] = cn
self.Map.region["ewres"] = (newreg['e'] - newreg['w']) / self.Map.width
- self.Map.region["nsres"] = (newreg['n'] - newreg['s']) / self.Map.height
+ self.Map.region["nsres"] = (
+ newreg['n'] - newreg['s']) / self.Map.height
self.Map.AlignExtentFromDisplay()
self.MapWindow.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
- self.Map.region['e'], self.Map.region['w'])
+ self.Map.region['e'], self.Map.region['w'])
if self.MapWindow.redrawAll is False:
self.MapWindow.redrawAll = True
@@ -1868,11 +2051,13 @@
zoommenu = wx.Menu()
# Add items to the menu
- zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust source display to target display'))
+ zoomsource = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+ 'Adjust source display to target display'))
zoommenu.AppendItem(zoomsource)
self.Bind(wx.EVT_MENU, self.OnZoomToTarget, zoomsource)
- zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _('Adjust target display to source display'))
+ zoomtarget = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+ 'Adjust target display to source display'))
zoommenu.AppendItem(zoomtarget)
self.Bind(wx.EVT_MENU, self.OnZoomToSource, zoomtarget)
@@ -1880,7 +2065,7 @@
# will be called before PopupMenu returns.
self.PopupMenu(zoommenu)
zoommenu.Destroy()
-
+
def OnSize(self, event):
"""Adjust Map Windows after GCP Map Display has been resized
"""
@@ -1909,10 +2094,11 @@
event.RequestMore()
pass
+
class GCPList(wx.ListCtrl,
CheckListCtrlMixin,
ListCtrlAutoWidthMixin):
-
+
def __init__(self, parent, gcp, id=wx.ID_ANY,
pos=wx.DefaultPosition, size=wx.DefaultSize,
style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_HRULES |
@@ -1920,7 +2106,7 @@
wx.ListCtrl.__init__(self, parent, id, pos, size, style)
- self.gcp = gcp # GCP class
+ self.gcp = gcp # GCP class
self.render = True
# Mixin settings
@@ -1929,7 +2115,7 @@
# TextEditMixin.__init__(self)
# tracks whether list items are checked or not
- self.CheckList = []
+ self.CheckList = []
self._Create()
@@ -1946,29 +2132,30 @@
# normal, simple columns
idx_col = 0
for col in (_('use'),
- _('source E'),
- _('source N'),
- _('target E'),
- _('target N'),
- _('Forward error'),
- _('Backward error')):
+ _('source E'),
+ _('source N'),
+ _('target E'),
+ _('target N'),
+ _('Forward error'),
+ _('Backward error')):
self.InsertColumn(idx_col, col)
idx_col += 1
else:
# the hard way: we want images on the column header
info = wx.ListItem()
- info.SetMask(wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
+ info.SetMask(
+ wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT)
info.SetImage(-1)
info.m_format = wx.LIST_FORMAT_LEFT
idx_col = 0
for lbl in (_('use'),
- _('source E'),
- _('source N'),
- _('target E'),
- _('target N'),
- _('Forward error'),
- _('Backward error')):
+ _('source E'),
+ _('source N'),
+ _('target E'),
+ _('target N'),
+ _('Forward error'),
+ _('Backward error')):
info.SetText(lbl)
self.InsertColumnInfo(idx_col, info)
idx_col += 1
@@ -2007,7 +2194,7 @@
if self.gcp.show_target:
targetMapWin = self.gcp.TgtMapWindow
targetMapWin.UpdateMap(render=False, renderVector=False)
-
+
def AddGCPItem(self):
"""
Appends an item to GCP list
@@ -2030,10 +2217,12 @@
wx.LIST_STATE_SELECTED)
self.ResizeColumns()
-
- self.gcp.pointsToDrawSrc.AddItem(coords = [0,0], label = str(self.selectedkey))
- self.gcp.pointsToDrawTgt.AddItem(coords = [0,0], label = str(self.selectedkey))
-
+
+ self.gcp.pointsToDrawSrc.AddItem(
+ coords=[0, 0], label=str(self.selectedkey))
+ self.gcp.pointsToDrawTgt.AddItem(
+ coords=[0, 0], label=str(self.selectedkey))
+
self.EnsureVisible(self.selected)
return self.selected
@@ -2046,16 +2235,16 @@
key = self.GetItemData(self.selected)
self.DeleteItem(self.selected)
-
+
if self.selected != wx.NOT_FOUND:
item = self.gcp.pointsToDrawSrc.GetItem(key - 1)
self.gcp.pointsToDrawSrc.DeleteItem(item)
-
+
item = self.gcp.pointsToDrawTgt.GetItem(key - 1)
self.gcp.pointsToDrawTgt.DeleteItem(item)
-
+
return key
-
+
def ResizeColumns(self):
"""Resize columns"""
minWidth = [90, 120]
@@ -2064,7 +2253,7 @@
# first column is checkbox, don't set to minWidth
if i > 0 and self.GetColumnWidth(i) < minWidth[i > 4]:
self.SetColumnWidth(i, minWidth[i > 4])
-
+
self.SendSizeEvent()
def GetSelected(self):
@@ -2099,11 +2288,11 @@
dlg = EditGCP(parent=self, id=wx.ID_ANY, data=coords, gcpno=key)
if dlg.ShowModal() == wx.ID_OK:
- values = dlg.GetValues() # string
-
+ values = dlg.GetValues() # string
+
if len(values) == 0:
- GError(parent = self,
- message=_("Invalid coordinate value. Operation canceled."))
+ GError(parent=self, message=_(
+ "Invalid coordinate value. Operation canceled."))
else:
for i in range(len(values)):
if values[i] != coords[i]:
@@ -2122,39 +2311,41 @@
float(values[3]),
0.0,
0.0]
-
- self.gcp.pointsToDrawSrc.GetItem(key - 1).SetCoords([float(values[0]),
- float(values[1])])
- self.gcp.pointsToDrawTgt.GetItem(key - 1).SetCoords([float(values[2]),
- float(values[3])])
+
+ self.gcp.pointsToDrawSrc.GetItem(
+ key - 1).SetCoords([float(values[0]), float(values[1])])
+ self.gcp.pointsToDrawTgt.GetItem(
+ key - 1).SetCoords([float(values[2]), float(values[3])])
self.gcp.UpdateColours()
-
+
def OnColClick(self, event):
"""ListCtrl forgets selected item..."""
self.selected = self.FindItemData(-1, self.selectedkey)
self.SetItemState(self.selected,
wx.LIST_STATE_SELECTED,
wx.LIST_STATE_SELECTED)
-
+
event.Skip()
+
class VectGroup(wx.Dialog):
"""Dialog to create a vector group (VREF file) for georectifying
.. todo::
Replace by g.group
"""
+
def __init__(self, parent, id, grassdb, location, mapset, group,
style=wx.DEFAULT_DIALOG_STYLE):
-
+
wx.Dialog.__init__(self, parent, id, style=style,
- title = _("Create vector map group"))
-
+ title=_("Create vector map group"))
+
self.grassdatabase = grassdb
self.xylocation = location
self.xymapset = mapset
self.xygroup = group
-
+
#
# get list of valid vector directories
#
@@ -2164,15 +2355,15 @@
'vector'))
for dir in vectlist:
if not os.path.isfile(os.path.join(self.grassdatabase,
- self.xylocation,
- self.xymapset,
- 'vector',
- dir,
- 'coor')):
+ self.xylocation,
+ self.xymapset,
+ 'vector',
+ dir,
+ 'coor')):
vectlist.remove(dir)
-
+
utils.ListSortLower(vectlist)
-
+
# path to vref file
self.vgrpfile = os.path.join(self.grassdatabase,
self.xylocation,
@@ -2180,23 +2371,22 @@
'group',
self.xygroup,
'VREF')
-
+
#
# buttons
#
- self.btnCancel = wx.Button(parent = self,
- id = wx.ID_CANCEL)
- self.btnOK = wx.Button(parent = self,
- id = wx.ID_OK)
+ self.btnCancel = wx.Button(parent=self,
+ id=wx.ID_CANCEL)
+ self.btnOK = wx.Button(parent=self,
+ id=wx.ID_OK)
self.btnOK.SetDefault()
-
#
# list of vector maps
#
- self.listMap = wx.CheckListBox(parent = self, id = wx.ID_ANY,
- choices = vectlist)
-
+ self.listMap = wx.CheckListBox(parent=self, id=wx.ID_ANY,
+ choices=vectlist)
+
if os.path.isfile(self.vgrpfile):
f = open(self.vgrpfile)
try:
@@ -2209,64 +2399,71 @@
self.listMap.SetCheckedStrings(checked)
finally:
f.close()
-
- line = wx.StaticLine(parent = self,
- id = wx.ID_ANY, size = (20, -1),
- style = wx.LI_HORIZONTAL)
+ line = wx.StaticLine(parent=self,
+ id=wx.ID_ANY, size=(20, -1),
+ style=wx.LI_HORIZONTAL)
+
#
# layout
#
sizer = wx.BoxSizer(wx.VERTICAL)
-
+
box = wx.BoxSizer(wx.HORIZONTAL)
- box.Add(item = wx.StaticText(parent = self, id = wx.ID_ANY,
- label = _('Select vector map(s) to add to group:')),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
- border = 5)
+ box.Add(
+ item=wx.StaticText(
+ parent=self,
+ id=wx.ID_ANY,
+ label=_('Select vector map(s) to add to group:')),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ border=5)
- box.Add(item = self.listMap,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
- border = 5)
+ box.Add(item=self.listMap,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT | wx.LEFT,
+ border=5)
-
- sizer.Add(box, flag = wx.ALIGN_RIGHT | wx.ALL,
- border = 3)
-
- sizer.Add(item = line, proportion = 0,
- flag = wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
- border = 5)
-
+ sizer.Add(box, flag=wx.ALIGN_RIGHT | wx.ALL,
+ border=3)
+
+ sizer.Add(item=line, proportion=0,
+ flag=wx.GROW | wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.RIGHT,
+ border=5)
+
# buttons
btnSizer = wx.StdDialogButtonSizer()
btnSizer.AddButton(self.btnCancel)
btnSizer.AddButton(self.btnOK)
btnSizer.Realize()
- sizer.Add(item = btnSizer, proportion = 0,
- flag = wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
- border = 5)
-
+ sizer.Add(item=btnSizer, proportion=0,
+ flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER,
+ border=5)
+
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()
-
+
def MakeVGroup(self):
"""Create VREF file"""
vgrouplist = []
for item in range(self.listMap.GetCount()):
if not self.listMap.IsChecked(item):
continue
- vgrouplist.append(self.listMap.GetString(item) + '@' + self.xymapset)
-
+ vgrouplist.append(
+ self.listMap.GetString(item) +
+ '@' +
+ self.xymapset)
+
f = open(self.vgrpfile, mode='w')
try:
for vect in vgrouplist:
f.write(vect + '\n')
finally:
f.close()
-
+
+
class EditGCP(wx.Dialog):
+
def __init__(self, parent, data, gcpno, id=wx.ID_ANY,
title=_("Edit GCP"),
style=wx.DEFAULT_DIALOG_STYLE):
@@ -2278,13 +2475,14 @@
sizer = wx.BoxSizer(wx.VERTICAL)
- box = wx.StaticBox (parent=panel, id=wx.ID_ANY,
- label=" %s %s " % (_("Ground Control Point No."), str(gcpno)))
+ box = wx.StaticBox(
+ parent=panel, id=wx.ID_ANY, label=" %s %s " %
+ (_("Ground Control Point No."), str(gcpno)))
boxSizer = wx.StaticBoxSizer(box, wx.VERTICAL)
# source coordinates
gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
-
+
self.xcoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
self.ycoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
self.ecoord = wx.TextCtrl(parent=panel, id=wx.ID_ANY, size=(150, -1))
@@ -2294,7 +2492,7 @@
tmp_coord = data[1]
data[1] = data[2]
data[2] = tmp_coord
-
+
row = 0
col = 0
idx = 0
@@ -2322,7 +2520,7 @@
col = 0
boxSizer.Add(item=gridSizer, proportion=1,
- flag=wx.EXPAND | wx.ALL, border=5)
+ flag=wx.EXPAND | wx.ALL, border=5)
sizer.Add(item=boxSizer, proportion=1,
flag=wx.EXPAND | wx.ALL, border=5)
@@ -2364,9 +2562,12 @@
return valuelist
+
class GrSettingsDialog(wx.Dialog):
- def __init__(self, parent, id, giface, title, pos=wx.DefaultPosition, size=wx.DefaultSize,
- style=wx.DEFAULT_DIALOG_STYLE):
+
+ def __init__(
+ self, parent, id, giface, title, pos=wx.DefaultPosition,
+ size=wx.DefaultSize, style=wx.DEFAULT_DIALOG_STYLE):
wx.Dialog.__init__(self, parent, id, title, pos, size, style)
"""
Dialog to set profile text options: font, title
@@ -2377,16 +2578,16 @@
#
self.parent = parent
self.new_src_map = src_map
- self.new_tgt_map = { 'raster' : tgt_map['raster'],
- 'vector' : tgt_map['vector'] }
+ self.new_tgt_map = {'raster': tgt_map['raster'],
+ 'vector': tgt_map['vector']}
self.sdfactor = 0
self.symbol = {}
-
+
self.methods = ["nearest",
"linear",
"linear_f",
- "cubic",
+ "cubic",
"cubic_f",
"lanczos",
"lanczos_f"]
@@ -2406,7 +2607,8 @@
btnApply.Bind(wx.EVT_BUTTON, self.OnApply)
btnApply.SetToolTipString(_("Apply changes for the current session"))
btnSave.Bind(wx.EVT_BUTTON, self.OnSave)
- btnSave.SetToolTipString(_("Apply and save changes to user settings file (default for next sessions)"))
+ btnSave.SetToolTipString(
+ _("Apply and save changes to user settings file (default for next sessions)"))
btnClose.Bind(wx.EVT_BUTTON, self.OnClose)
btnClose.SetToolTipString(_("Close dialog"))
@@ -2415,17 +2617,21 @@
btnSizer.Add(btnApply, flag=wx.LEFT | wx.RIGHT, border=5)
btnSizer.Add(btnSave, flag=wx.LEFT | wx.RIGHT, border=5)
btnSizer.Add(btnClose, flag=wx.LEFT | wx.RIGHT, border=5)
-
+
# sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
- mainSizer.Add(item=notebook, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
+ mainSizer.Add(
+ item=notebook,
+ proportion=1,
+ flag=wx.EXPAND | wx.ALL,
+ border=5)
mainSizer.Add(item=btnSizer, proportion=0,
- flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
+ flag=wx.ALIGN_RIGHT | wx.ALL, border=5)
# flag=wx.EXPAND | wx.ALL | wx.ALIGN_CENTER, border=5)
self.SetSizer(mainSizer)
mainSizer.Fit(self)
-
+
def __CreateSymbologyPage(self, notebook):
"""Create notebook page with symbology settings"""
@@ -2437,24 +2643,41 @@
rmsgridSizer = wx.GridBagSizer(vgap=5, hgap=5)
# highlight only highest forward RMS error
- self.highlighthighest = wx.CheckBox(parent=panel, id=wx.ID_ANY,
- label=_("Highlight highest RMS error only"))
+ self.highlighthighest = wx.CheckBox(
+ parent=panel, id=wx.ID_ANY,
+ label=_("Highlight highest RMS error only"))
hh = UserSettings.Get(group='gcpman', key='rms', subkey='highestonly')
self.highlighthighest.SetValue(hh)
- rmsgridSizer.Add(item=self.highlighthighest, flag=wx.ALIGN_CENTER_VERTICAL, pos=(0, 0))
+ rmsgridSizer.Add(
+ item=self.highlighthighest,
+ flag=wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ 0,
+ 0))
# RMS forward error threshold
- rmslabel = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Highlight RMS error > M + SD * factor:"))
- rmslabel.SetToolTip(wx.ToolTip(_("Highlight GCPs with an RMS error larger than \n"
- "mean + standard deviation * given factor. \n"
- "Recommended values for this factor are between 1 and 2.")))
- rmsgridSizer.Add(item=rmslabel, flag=wx.ALIGN_CENTER_VERTICAL, pos=(1, 0))
- sdfactor = UserSettings.Get(group='gcpman', key='rms', subkey='sdfactor')
+ rmslabel = wx.StaticText(
+ parent=panel, id=wx.ID_ANY,
+ label=_("Highlight RMS error > M + SD * factor:"))
+ rmslabel.SetToolTip(
+ wx.ToolTip(
+ _(
+ "Highlight GCPs with an RMS error larger than \n"
+ "mean + standard deviation * given factor. \n"
+ "Recommended values for this factor are between 1 and 2.")))
+ rmsgridSizer.Add(
+ item=rmslabel,
+ flag=wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ 1,
+ 0))
+ sdfactor = UserSettings.Get(
+ group='gcpman', key='rms', subkey='sdfactor')
self.rmsWin = wx.TextCtrl(parent=panel, id=wx.ID_ANY,
- size=(70,-1), style=wx.TE_NOHIDESEL)
+ size=(70, -1), style=wx.TE_NOHIDESEL)
self.rmsWin.SetValue("%s" % str(sdfactor))
if (self.parent.highest_only == True):
- self.rmsWin.Disable()
+ self.rmsWin.Disable()
self.symbol['sdfactor'] = self.rmsWin.GetId()
rmsgridSizer.Add(item=self.rmsWin, flag=wx.ALIGN_RIGHT, pos=(1, 1))
@@ -2487,14 +2710,17 @@
# symbol color for high forward RMS error
#
row += 1
- label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for high RMS error:"))
+ label = wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Color for high RMS error:"))
gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
hcol = UserSettings.Get(group='gcpman', key='symbol', subkey='hcolor')
hcolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
- colour=wx.Colour(hcol[0],
- hcol[1],
- hcol[2],
- 255))
+ colour=wx.Colour(hcol[0],
+ hcol[1],
+ hcol[2],
+ 255))
self.symbol['hcolor'] = hcolWin.GetId()
gridSizer.Add(item=hcolWin,
flag=wx.ALIGN_RIGHT,
@@ -2504,14 +2730,17 @@
# symbol color for selected GCP
#
row += 1
- label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for selected GCP:"))
+ label = wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Color for selected GCP:"))
gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
scol = UserSettings.Get(group='gcpman', key='symbol', subkey='scolor')
scolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
- colour=wx.Colour(scol[0],
- scol[1],
- scol[2],
- 255))
+ colour=wx.Colour(scol[0],
+ scol[1],
+ scol[2],
+ 255))
self.symbol['scolor'] = scolWin.GetId()
gridSizer.Add(item=scolWin,
flag=wx.ALIGN_RIGHT,
@@ -2521,14 +2750,17 @@
# symbol color for unused GCP
#
row += 1
- label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Color for unused GCPs:"))
+ label = wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Color for unused GCPs:"))
gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
ucol = UserSettings.Get(group='gcpman', key='symbol', subkey='ucolor')
ucolWin = csel.ColourSelect(parent=panel, id=wx.ID_ANY,
- colour=wx.Colour(ucol[0],
- ucol[1],
- ucol[2],
- 255))
+ colour=wx.Colour(ucol[0],
+ ucol[1],
+ ucol[2],
+ 255))
self.symbol['ucolor'] = ucolWin.GetId()
gridSizer.Add(item=ucolWin,
flag=wx.ALIGN_RIGHT,
@@ -2537,33 +2769,52 @@
# show unused GCPs
row += 1
self.showunused = wx.CheckBox(parent=panel, id=wx.ID_ANY,
- label=_("Show unused GCPs"))
+ label=_("Show unused GCPs"))
shuu = UserSettings.Get(group='gcpman', key='symbol', subkey='unused')
self.showunused.SetValue(shuu)
- gridSizer.Add(item=self.showunused, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
+ gridSizer.Add(
+ item=self.showunused,
+ flag=wx.ALIGN_CENTER_VERTICAL,
+ pos=(
+ row,
+ 0))
#
# symbol size
#
row += 1
- label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Symbol size:"))
+ label = wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Symbol size:"))
gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- symsize = int(UserSettings.Get(group='gcpman', key='symbol', subkey='size'))
+ symsize = int(
+ UserSettings.Get(
+ group='gcpman',
+ key='symbol',
+ subkey='size'))
sizeWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
- min=1, max=20)
+ min=1, max=20)
sizeWin.SetValue(symsize)
self.symbol['size'] = sizeWin.GetId()
gridSizer.Add(item=sizeWin,
flag=wx.ALIGN_RIGHT,
pos=(row, 1))
-
+
#
# symbol width
#
row += 1
- label = wx.StaticText(parent=panel, id=wx.ID_ANY, label=_("Line width:"))
+ label = wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_("Line width:"))
gridSizer.Add(item=label, flag=wx.ALIGN_CENTER_VERTICAL, pos=(row, 0))
- width = int(UserSettings.Get(group='gcpman', key='symbol', subkey='width'))
+ width = int(
+ UserSettings.Get(
+ group='gcpman',
+ key='symbol',
+ subkey='width'))
widWin = wx.SpinCtrl(parent=panel, id=wx.ID_ANY,
min=1, max=10)
widWin.SetValue(width)
@@ -2572,7 +2823,7 @@
flag=wx.ALIGN_RIGHT,
pos=(row, 1))
gridSizer.AddGrowableCol(1)
-
+
boxSizer.Add(item=gridSizer, flag=wx.EXPAND)
sizer.Add(item=boxSizer, flag=wx.EXPAND | wx.ALL, border=5)
@@ -2580,39 +2831,72 @@
# maps to display
#
# source map to display
- self.srcselection = Select(panel, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type='maptype', updateOnPopup = False)
+ self.srcselection = Select(
+ panel,
+ id=wx.ID_ANY,
+ size=globalvar.DIALOG_GSELECT_SIZE,
+ type='maptype',
+ updateOnPopup=False)
self.parent.grwiz.SwitchEnv('source')
self.srcselection.SetElementList(maptype)
# filter out all maps not in group
- self.srcselection.tcp.GetElementList(elements = self.parent.src_maps)
+ self.srcselection.tcp.GetElementList(elements=self.parent.src_maps)
# target map(s) to display
self.parent.grwiz.SwitchEnv('target')
- self.tgtrastselection = Select(panel, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type='raster', updateOnPopup = False)
+ self.tgtrastselection = Select(
+ panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+ type='raster', updateOnPopup=False)
self.tgtrastselection.SetElementList('cell')
self.tgtrastselection.GetElementList()
- self.tgtvectselection = Select(panel, id=wx.ID_ANY,
- size=globalvar.DIALOG_GSELECT_SIZE, type='vector', updateOnPopup = False)
+ self.tgtvectselection = Select(
+ panel, id=wx.ID_ANY, size=globalvar.DIALOG_GSELECT_SIZE,
+ type='vector', updateOnPopup=False)
self.tgtvectselection.SetElementList('vector')
self.tgtvectselection.GetElementList()
- sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select source map to display:')),
- proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
- sizer.Add(item=self.srcselection, proportion=0,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ sizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_('Select source map to display:')),
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
+ sizer.Add(
+ item=self.srcselection,
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
self.srcselection.SetValue(src_map)
- sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target raster map to display:')),
- proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
- sizer.Add(item=self.tgtrastselection, proportion=0,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ sizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_('Select target raster map to display:')),
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
+ sizer.Add(
+ item=self.tgtrastselection,
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
self.tgtrastselection.SetValue(tgt_map['raster'])
- sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select target vector map to display:')),
- proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
- sizer.Add(item=self.tgtvectselection, proportion=0,
- flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ sizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_('Select target vector map to display:')),
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
+ sizer.Add(
+ item=self.tgtvectselection,
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
self.tgtvectselection.SetValue(tgt_map['vector'])
# bindings
@@ -2623,7 +2907,7 @@
self.tgtvectselection.Bind(wx.EVT_TEXT, self.OnTgtVectSelection)
panel.SetSizer(sizer)
-
+
return panel
def __CreateRectificationPage(self, notebook):
@@ -2635,40 +2919,65 @@
sizer = wx.BoxSizer(wx.VERTICAL)
# transformation order
- self.rb_grorder = wx.RadioBox(parent=panel, id=wx.ID_ANY,
- label=" %s " % _("Select rectification order"),
- choices=[_('1st order'), _('2nd order'), _('3rd order')],
- majorDimension=wx.RA_SPECIFY_COLS)
+ self.rb_grorder = wx.RadioBox(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=" %s " %
+ _("Select rectification order"),
+ choices=[
+ _('1st order'),
+ _('2nd order'),
+ _('3rd order')],
+ majorDimension=wx.RA_SPECIFY_COLS)
sizer.Add(item=self.rb_grorder, proportion=0,
- flag=wx.EXPAND | wx.ALL, border=5)
+ flag=wx.EXPAND | wx.ALL, border=5)
self.rb_grorder.SetSelection(self.parent.gr_order - 1)
# interpolation method
gridSizer = wx.GridBagSizer(vgap=5, hgap=5)
- gridSizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Select interpolation method:')),
- pos=(0,0), flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ gridSizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_('Select interpolation method:')),
+ pos=(
+ 0,
+ 0),
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
self.grmethod = wx.Choice(parent=panel, id=wx.ID_ANY,
- choices = self.methods)
- gridSizer.Add(item=self.grmethod, pos=(0,1),
- flag=wx.ALIGN_RIGHT, border=5)
+ choices=self.methods)
+ gridSizer.Add(item=self.grmethod, pos=(0, 1),
+ flag=wx.ALIGN_RIGHT, border=5)
self.grmethod.SetStringSelection(self.parent.gr_method)
gridSizer.AddGrowableCol(1)
sizer.Add(item=gridSizer, flag=wx.EXPAND | wx.ALL, border=5)
# clip to region
- self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY,
- label=_("clip to computational region in target location"))
+ self.check = wx.CheckBox(parent=panel, id=wx.ID_ANY, label=_(
+ "clip to computational region in target location"))
sizer.Add(item=self.check, proportion=0,
- flag=wx.EXPAND | wx.ALL, border=5)
+ flag=wx.EXPAND | wx.ALL, border=5)
self.check.SetValue(self.parent.clip_to_region)
# extension
- sizer.Add(item=wx.StaticText(parent=panel, id=wx.ID_ANY, label=_('Extension for output maps:')),
- proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
- self.ext_txt = wx.TextCtrl(parent=panel, id=wx.ID_ANY, value="", size=(350,-1))
+ sizer.Add(
+ item=wx.StaticText(
+ parent=panel,
+ id=wx.ID_ANY,
+ label=_('Extension for output maps:')),
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
+ self.ext_txt = wx.TextCtrl(
+ parent=panel, id=wx.ID_ANY, value="", size=(
+ 350, -1))
self.ext_txt.SetValue(self.parent.extension)
- sizer.Add(item=self.ext_txt,
- proportion=0, flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, border=5)
+ sizer.Add(
+ item=self.ext_txt,
+ proportion=0,
+ flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=5)
# bindings
self.ext_txt.Bind(wx.EVT_TEXT, self.OnExtension)
@@ -2677,7 +2986,7 @@
self.Bind(wx.EVT_CHECKBOX, self.OnClipRegion, self.check)
panel.SetSizer(sizer)
-
+
return panel
def OnHighlight(self, event):
@@ -2689,36 +2998,36 @@
self.parent.highest_only = False
self.rmsWin.Enable()
- def OnSDFactor(self,event):
+ def OnSDFactor(self, event):
"""New factor for RMS threshold = M + SD * factor"""
try:
self.sdfactor = float(self.rmsWin.GetValue())
except ValueError:
return
if self.sdfactor <= 0:
- GError(parent = self,
+ GError(parent=self,
message=_('RMS threshold factor must be > 0'))
elif self.sdfactor < 1:
- GError(parent = self,
+ GError(parent=self,
message=_('RMS threshold factor is < 1\n'
'Too many points might be highlighted'))
-
- def OnSrcSelection(self,event):
+
+ def OnSrcSelection(self, event):
"""Source map to display selected"""
global src_map
tmp_map = self.srcselection.GetValue()
-
+
if not tmp_map == '' and not tmp_map == src_map:
self.new_src_map = tmp_map
- def OnTgtRastSelection(self,event):
+ def OnTgtRastSelection(self, event):
"""Target map to display selected"""
global tgt_map
self.new_tgt_map['raster'] = self.tgtrastselection.GetValue()
- def OnTgtVectSelection(self,event):
+ def OnTgtVectSelection(self, event):
"""Target map to display selected"""
global tgt_map
@@ -2729,7 +3038,7 @@
def OnClipRegion(self, event):
self.parent.clip_to_region = event.IsChecked()
-
+
def OnExtension(self, event):
self.parent.extension = self.ext_txt.GetValue()
@@ -2740,32 +3049,60 @@
layers = None
- UserSettings.Set(group = 'gcpman', key = 'rms', subkey = 'highestonly',
- value = self.highlighthighest.GetValue())
-
+ UserSettings.Set(group='gcpman', key='rms', subkey='highestonly',
+ value=self.highlighthighest.GetValue())
+
if self.sdfactor > 0:
UserSettings.Set(group='gcpman', key='rms', subkey='sdfactor',
value=self.sdfactor)
-
+
self.parent.sdfactor = self.sdfactor
if self.parent.rmsthresh > 0:
self.parent.rmsthresh = self.parent.rmsmean + self.parent.sdfactor * self.parent.rmssd
-
- UserSettings.Set(group='gcpman', key='symbol', subkey='color',
- value=tuple(wx.FindWindowById(self.symbol['color']).GetColour()))
- UserSettings.Set(group='gcpman', key='symbol', subkey='hcolor',
- value=tuple(wx.FindWindowById(self.symbol['hcolor']).GetColour()))
- UserSettings.Set(group='gcpman', key='symbol', subkey='scolor',
- value=tuple(wx.FindWindowById(self.symbol['scolor']).GetColour()))
- UserSettings.Set(group='gcpman', key='symbol', subkey='ucolor',
- value=tuple(wx.FindWindowById(self.symbol['ucolor']).GetColour()))
+
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='color',
+ value=tuple(
+ wx.FindWindowById(
+ self.symbol['color']).GetColour()))
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='hcolor',
+ value=tuple(
+ wx.FindWindowById(
+ self.symbol['hcolor']).GetColour()))
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='scolor',
+ value=tuple(
+ wx.FindWindowById(
+ self.symbol['scolor']).GetColour()))
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='ucolor',
+ value=tuple(
+ wx.FindWindowById(
+ self.symbol['ucolor']).GetColour()))
UserSettings.Set(group='gcpman', key='symbol', subkey='unused',
value=self.showunused.GetValue())
- UserSettings.Set(group='gcpman', key='symbol', subkey='size',
- value=wx.FindWindowById(self.symbol['size']).GetValue())
- UserSettings.Set(group='gcpman', key='symbol', subkey='width',
- value=wx.FindWindowById(self.symbol['width']).GetValue())
-
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='size',
+ value=wx.FindWindowById(
+ self.symbol['size']).GetValue())
+ UserSettings.Set(
+ group='gcpman',
+ key='symbol',
+ subkey='width',
+ value=wx.FindWindowById(
+ self.symbol['width']).GetValue())
+
srcrender = False
srcrenderVector = False
tgtrender = False
@@ -2775,7 +3112,7 @@
# remove old layer
layers = self.parent.grwiz.SrcMap.GetListOfLayers()
self.parent.grwiz.SrcMap.DeleteLayer(layers[0])
-
+
src_map = self.new_src_map
if maptype == 'raster':
cmdlist = ['d.rast', 'map=%s' % src_map]
@@ -2785,8 +3122,9 @@
srcrenderVector = True
self.parent.grwiz.SwitchEnv('source')
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.parent.grwiz.SrcMap.AddLayer(ltype=maptype, command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
+ self.parent.grwiz.SrcMap.AddLayer(
+ ltype=maptype, command=cmdlist, active=True, name=name,
+ hidden=False, opacity=1.0, render=False)
self.parent.grwiz.SwitchEnv('target')
@@ -2798,7 +3136,7 @@
self.parent.grwiz.TgtMap.DeleteLayer(layers[0])
del layers[0]
layers = self.parent.grwiz.TgtMap.GetListOfLayers()
- #self.parent.grwiz.TgtMap.DeleteAllLayers()
+ # self.parent.grwiz.TgtMap.DeleteAllLayers()
reload_target = True
tgt_map['raster'] = self.new_tgt_map['raster']
tgt_map['vector'] = self.new_tgt_map['vector']
@@ -2806,16 +3144,18 @@
if tgt_map['raster'] != '':
cmdlist = ['d.rast', 'map=%s' % tgt_map['raster']]
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.parent.grwiz.TgtMap.AddLayer(ltype='raster', command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
+ self.parent.grwiz.TgtMap.AddLayer(
+ ltype='raster', command=cmdlist, active=True, name=name,
+ hidden=False, opacity=1.0, render=False)
tgtrender = True
if tgt_map['vector'] != '':
cmdlist = ['d.vect', 'map=%s' % tgt_map['vector']]
name, found = utils.GetLayerNameFromCmd(cmdlist)
- self.parent.grwiz.TgtMap.AddLayer(ltype='vector', command=cmdlist, active=True,
- name=name, hidden=False, opacity=1.0, render=False)
+ self.parent.grwiz.TgtMap.AddLayer(
+ ltype='vector', command=cmdlist, active=True, name=name,
+ hidden=False, opacity=1.0, render=False)
tgtrenderVector = True
@@ -2826,7 +3166,7 @@
self.parent._mgr.Update()
self.parent.activemap.SetSelection(0)
self.parent.activemap.Enable(False)
- self.parent.GetMapToolbar().Enable('zoommenu', enable = False)
+ self.parent.GetMapToolbar().Enable('zoommenu', enable=False)
else:
if self.parent.show_target == False:
self.parent.show_target = True
@@ -2834,12 +3174,17 @@
self.parent._mgr.Update()
self.parent.activemap.SetSelection(0)
self.parent.activemap.Enable(True)
- self.parent.GetMapToolbar().Enable('zoommenu', enable = True)
- self.parent.TgtMapWindow.ZoomToMap(layers = self.parent.TgtMap.GetListOfLayers())
-
- self.parent.UpdateColours(srcrender, srcrenderVector, tgtrender, tgtrenderVector)
- self.parent.SetSettings()
+ self.parent.GetMapToolbar().Enable('zoommenu', enable=True)
+ self.parent.TgtMapWindow.ZoomToMap(
+ layers=self.parent.TgtMap.GetListOfLayers())
+ self.parent.UpdateColours(
+ srcrender,
+ srcrenderVector,
+ tgtrender,
+ tgtrenderVector)
+ self.parent.SetSettings()
+
def OnSave(self, event):
"""Button 'Save' pressed"""
self.UpdateSettings()
@@ -2847,13 +3192,15 @@
UserSettings.ReadSettingsFile(settings=fileSettings)
fileSettings['gcpman'] = UserSettings.Get(group='gcpman')
file = UserSettings.SaveToFile(fileSettings)
- self.parent._giface.WriteLog(_('GCP Manager settings saved to file \'%s\'.') % file)
- #self.Close()
+ self.parent._giface.WriteLog(
+ _('GCP Manager settings saved to file \'%s\'.') %
+ file)
+ # self.Close()
def OnApply(self, event):
"""Button 'Apply' pressed"""
self.UpdateSettings()
- #self.Close()
+ # self.Close()
def OnClose(self, event):
"""Button 'Cancel' pressed"""
Modified: grass/trunk/gui/wxpython/gcp/mapdisplay.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/mapdisplay.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/mapdisplay.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -23,14 +23,14 @@
import wx
import wx.aui
-from mapdisp.toolbars import MapToolbar
-from gcp.toolbars import GCPDisplayToolbar, GCPManToolbar
-from mapdisp.gprint import PrintOptions
-from core.gcmd import GMessage
+from mapdisp.toolbars import MapToolbar
+from gcp.toolbars import GCPDisplayToolbar, GCPManToolbar
+from mapdisp.gprint import PrintOptions
+from core.gcmd import GMessage
from core.utils import _
-from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
-from gui_core.mapdisp import SingleMapFrame
-from core.settings import UserSettings
+from gui_core.dialogs import GetImageHandlers, ImageSizeDialog
+from gui_core.mapdisp import SingleMapFrame
+from core.settings import UserSettings
from mapwin.buffered import BufferedMapWindow
from mapwin.base import MapWindowProperties
@@ -40,10 +40,12 @@
# for standalone app
cmdfilename = None
+
class MapFrame(SingleMapFrame):
"""Main frame for map display window. Drawing takes place in
child double buffered drawing window.
"""
+
def __init__(self, parent, giface,
title=_("GRASS GIS Manage Ground Control Points"),
toolbars=["gcpdisp"], Map=None, auimgr=None,
@@ -58,10 +60,17 @@
:param auimgs: AUI manager
:param kwargs: wx.Frame attribures
"""
-
- SingleMapFrame.__init__(self, parent = parent, giface = giface, title = title,
- Map = Map, auimgr = auimgr, name = name, **kwargs)
+ SingleMapFrame.__init__(
+ self,
+ parent=parent,
+ giface=giface,
+ title=title,
+ Map=Map,
+ auimgr=auimgr,
+ name=name,
+ **kwargs)
+
self._giface = giface
# properties are shared in other objects, so defining here
self.mapWindowProperties = MapWindowProperties()
@@ -76,15 +85,15 @@
self.activemap = self.toolbars['gcpdisp'].togglemap
self.activemap.SetSelection(0)
-
- self.SrcMap = self.grwiz.SrcMap # instance of render.Map
- self.TgtMap = self.grwiz.TgtMap # instance of render.Map
+
+ self.SrcMap = self.grwiz.SrcMap # instance of render.Map
+ self.TgtMap = self.grwiz.TgtMap # instance of render.Map
self._mgr.SetDockSizeConstraint(0.5, 0.5)
#
# Add statusbar
#
-
+
# items for choice
self.statusbarItems = [sb.SbCoordinates,
sb.SbRegionExtent,
@@ -96,32 +105,35 @@
sb.SbProjection,
sbgcp.SbGoToGCP,
sbgcp.SbRMSError]
-
-
+
# create statusbar and its manager
- statusbar = self.CreateStatusBar(number = 4, style = 0)
+ statusbar = self.CreateStatusBar(number=4, style=0)
statusbar.SetStatusWidths([-5, -2, -1, -1])
- self.statusbarManager = sb.SbManager(mapframe = self, statusbar = statusbar)
-
+ self.statusbarManager = sb.SbManager(
+ mapframe=self, statusbar=statusbar)
+
# fill statusbar manager
- self.statusbarManager.AddStatusbarItemsByClass(self.statusbarItems, mapframe = self, statusbar = statusbar)
- self.statusbarManager.AddStatusbarItem(sb.SbMask(self, statusbar = statusbar, position = 2))
- self.statusbarManager.AddStatusbarItem(sb.SbRender(self, statusbar = statusbar, position = 3))
-
- self.statusbarManager.SetMode(8) # goto GCP
+ self.statusbarManager.AddStatusbarItemsByClass(
+ self.statusbarItems, mapframe=self, statusbar=statusbar)
+ self.statusbarManager.AddStatusbarItem(
+ sb.SbMask(self, statusbar=statusbar, position=2))
+ self.statusbarManager.AddStatusbarItem(
+ sb.SbRender(self, statusbar=statusbar, position=3))
+ self.statusbarManager.SetMode(8) # goto GCP
+
#
# Init map display (buffered DC & set default cursor)
#
self.grwiz.SwitchEnv('source')
- self.SrcMapWindow = BufferedMapWindow(parent=self, giface=self._giface, id=wx.ID_ANY,
- properties=self.mapWindowProperties,
- Map=self.SrcMap)
+ self.SrcMapWindow = BufferedMapWindow(
+ parent=self, giface=self._giface, id=wx.ID_ANY,
+ properties=self.mapWindowProperties, Map=self.SrcMap)
self.grwiz.SwitchEnv('target')
- self.TgtMapWindow = BufferedMapWindow(parent=self, giface=self._giface, id=wx.ID_ANY,
- properties=self.mapWindowProperties,
- Map=self.TgtMap)
+ self.TgtMapWindow = BufferedMapWindow(
+ parent=self, giface=self._giface, id=wx.ID_ANY,
+ properties=self.mapWindowProperties, Map=self.TgtMap)
self.MapWindow = self.SrcMapWindow
self.Map = self.SrcMap
self._setUpMapWindow(self.SrcMapWindow)
@@ -139,9 +151,9 @@
#
# initialize region values
#
- self._initMap(Map = self.SrcMap)
- self._initMap(Map = self.TgtMap)
-
+ self._initMap(Map=self.SrcMap)
+ self._initMap(Map=self.TgtMap)
+
self.GetMapToolbar().SelectDefault()
#
@@ -149,29 +161,30 @@
#
self.activemap.Bind(wx.EVT_CHOICE, self.OnUpdateActive)
self.Bind(wx.EVT_SIZE, self.OnSize)
-
+
#
# Update fancy gui style
#
- # AuiManager wants a CentrePane, workaround to get two equally sized windows
+ # AuiManager wants a CentrePane, workaround to get two equally sized
+ # windows
self.list = self.CreateGCPList()
#self.SrcMapWindow.SetSize((300, 300))
#self.TgtMapWindow.SetSize((300, 300))
self.list.SetSize((100, 150))
self._mgr.AddPane(self.list, wx.aui.AuiPaneInfo().
- Name("gcplist").Caption(_("GCP List")).LeftDockable(False).
- RightDockable(False).PinButton().FloatingSize((600,200)).
- CloseButton(False).DestroyOnClose(True).
- Top().Layer(1).MinSize((200,100)))
+ Name("gcplist").Caption(_("GCP List")).LeftDockable(False).
+ RightDockable(False).PinButton().FloatingSize((600, 200)).
+ CloseButton(False).DestroyOnClose(True).
+ Top().Layer(1).MinSize((200, 100)))
self._mgr.AddPane(self.SrcMapWindow, wx.aui.AuiPaneInfo().
- Name("source").Caption(_("Source Display")).Dockable(False).
- CloseButton(False).DestroyOnClose(True).Floatable(False).
- Centre())
+ Name("source").Caption(_("Source Display")).Dockable(False).
+ CloseButton(False).DestroyOnClose(True).Floatable(False).
+ Centre())
self._mgr.AddPane(self.TgtMapWindow, wx.aui.AuiPaneInfo().
- Name("target").Caption(_("Target Display")).Dockable(False).
- CloseButton(False).DestroyOnClose(True).Floatable(False).
- Right().Layer(0))
+ Name("target").Caption(_("Target Display")).Dockable(False).
+ CloseButton(False).DestroyOnClose(True).Floatable(False).
+ Right().Layer(0))
srcwidth, srcheight = self.SrcMapWindow.GetSize()
tgtwidth, tgtheight = self.TgtMapWindow.GetSize()
@@ -192,7 +205,7 @@
# Init print module and classes
#
self.printopt = PrintOptions(self, self.MapWindow)
-
+
#
# Initialization of digitization tool
#
@@ -201,7 +214,7 @@
# set active map
self.MapWindow = self.SrcMapWindow
self.Map = self.SrcMap
-
+
# do not init zoom history here, that happens when zooming to map(s)
#
@@ -213,7 +226,7 @@
self.dialogs['barscale'] = None
self.dialogs['legend'] = None
- self.decorationDialog = None # decoration/overlays
+ self.decorationDialog = None # decoration/overlays
# doing nice things in statusbar when other things are ready
self.statusbarManager.Update()
@@ -231,7 +244,7 @@
def AddToolbar(self, name):
"""Add defined toolbar to the window
-
+
Currently known toolbars are:
- 'map' - basic map toolbar
- 'vdigit' - vector digitizer
@@ -254,7 +267,8 @@
# GCP display
elif name == "gcpdisp":
- self.toolbars['gcpdisp'] = GCPDisplayToolbar(self, self._toolSwitcher)
+ self.toolbars['gcpdisp'] = GCPDisplayToolbar(
+ self, self._toolSwitcher)
self._mgr.AddPane(self.toolbars['gcpdisp'],
wx.aui.AuiPaneInfo().
@@ -265,7 +279,7 @@
CloseButton(False).Layer(2))
if self.show_target == False:
- self.toolbars['gcpdisp'].Enable('zoommenu', enable = False)
+ self.toolbars['gcpdisp'].Enable('zoommenu', enable=False)
self.toolbars['gcpman'] = GCPManToolbar(self)
@@ -276,7 +290,7 @@
LeftDockable(False).RightDockable(False).
BottomDockable(False).TopDockable(True).
CloseButton(False).Layer(2))
-
+
self._mgr.Update()
def OnUpdateProgress(self, event):
@@ -284,9 +298,9 @@
Update progress bar info
"""
self.GetProgressBar().UpdateProgress(event.layer, event.map)
-
+
event.Skip()
-
+
def OnFocus(self, event):
"""
Change choicebook page to match display.
@@ -304,8 +318,8 @@
def OnDraw(self, event):
"""Re-display current map composition
"""
- self.MapWindow.UpdateMap(render = False)
-
+ self.MapWindow.UpdateMap(render=False)
+
def OnRender(self, event):
"""Re-render map composition (each map layer)
"""
@@ -318,13 +332,13 @@
self.SrcMapWindow.UpdateMap(render=True)
if self.show_target:
self.TgtMapWindow.UpdateMap(render=True)
-
+
# update statusbar
self.StatusbarUpdate()
def OnPointer(self, event):
"""Pointer button clicked
- """
+ """
self.SrcMapWindow.SetModePointer()
self.TgtMapWindow.SetModePointer()
# change the default cursor
@@ -364,8 +378,8 @@
"""
img = self.MapWindow.img
if not img:
- GMessage(parent = self,
- message = _("Nothing to render (empty map). Operation canceled."))
+ GMessage(parent=self, message=_(
+ "Nothing to render (empty map). Operation canceled."))
return
filetype, ltype = GetImageHandlers(img)
@@ -377,29 +391,29 @@
return
width, height = dlg.GetValues()
dlg.Destroy()
-
+
# get filename
- dlg = wx.FileDialog(parent = self,
- message = _("Choose a file name to save the image "
- "(no need to add extension)"),
- wildcard = filetype,
+ dlg = wx.FileDialog(parent=self,
+ message=_("Choose a file name to save the image "
+ "(no need to add extension)"),
+ wildcard=filetype,
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
-
+
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
if not path:
dlg.Destroy()
return
-
+
base, ext = os.path.splitext(path)
fileType = ltype[dlg.GetFilterIndex()]['type']
- extType = ltype[dlg.GetFilterIndex()]['ext']
+ extType = ltype[dlg.GetFilterIndex()]['ext']
if ext != extType:
path = base + '.' + extType
-
+
self.MapWindow.SaveToFile(path, fileType,
width, height)
-
+
dlg.Destroy()
def PrintMenu(self, event):
@@ -430,25 +444,25 @@
"""
Set display extents to match selected raster map (ignore NULLs)
"""
- self.MapWindow.ZoomToMap(ignoreNulls = True)
-
+ self.MapWindow.ZoomToMap(ignoreNulls=True)
+
def OnZoomToSaved(self, event):
"""Set display geometry to match extents in
saved region file
"""
self.MapWindow.SetRegion(zoomOnly=True)
-
+
def OnDisplayToWind(self, event):
"""Set computational region (WIND file) to match display
extents
"""
self.MapWindow.DisplayToWind()
-
+
def SaveDisplayRegion(self, event):
"""Save display extents to named region file.
"""
self.MapWindow.SaveDisplayRegion()
-
+
def OnZoomMenu(self, event):
"""Popup Zoom menu
"""
@@ -456,11 +470,13 @@
zoommenu = wx.Menu()
# Add items to the menu
- zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to computational region (set with g.region)'))
+ zoomwind = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+ 'Zoom to computational region (set with g.region)'))
zoommenu.AppendItem(zoomwind)
self.Bind(wx.EVT_MENU, self.OnZoomToWind, zoomwind)
- zoomdefault = wx.MenuItem(zoommenu, wx.ID_ANY, _('Zoom to default region'))
+ zoomdefault = wx.MenuItem(
+ zoommenu, wx.ID_ANY, _('Zoom to default region'))
zoommenu.AppendItem(zoomdefault)
self.Bind(wx.EVT_MENU, self.OnZoomToDefault, zoomdefault)
@@ -468,11 +484,13 @@
zoommenu.AppendItem(zoomsaved)
self.Bind(wx.EVT_MENU, self.OnZoomToSaved, zoomsaved)
- savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _('Set computational region from display'))
+ savewind = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+ 'Set computational region from display'))
zoommenu.AppendItem(savewind)
self.Bind(wx.EVT_MENU, self.OnDisplayToWind, savewind)
- savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _('Save display geometry to named region'))
+ savezoom = wx.MenuItem(zoommenu, wx.ID_ANY, _(
+ 'Save display geometry to named region'))
zoommenu.AppendItem(savezoom)
self.Bind(wx.EVT_MENU, self.SaveDisplayRegion, savezoom)
@@ -480,13 +498,12 @@
# will be called before PopupMenu returns.
self.PopupMenu(zoommenu)
zoommenu.Destroy()
-
-
+
def IsStandalone(self):
"""Check if Map display is standalone"""
# we do not know and we do not care, so always False
return True
-
+
def GetLayerManager(self):
"""Get reference to Layer Manager
@@ -496,13 +513,13 @@
def GetSrcWindow(self):
return self.SrcMapWindow
-
+
def GetTgtWindow(self):
return self.TgtMapWindow
-
+
def GetShowTarget(self):
return self.show_target
-
+
def GetMapToolbar(self):
"""Returns toolbar with zooming tools"""
return self.toolbars['gcpdisp']
Modified: grass/trunk/gui/wxpython/gcp/statusbar.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/statusbar.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/statusbar.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -30,6 +30,7 @@
Requires MapFrame.GetSrcWindow, MapFrame.GetTgtWindow,
MapFrame.GetListCtrl, MapFrame.GetMapCoordList.
"""
+
def __init__(self, mapframe, statusbar, position=0):
SbItem.__init__(self, mapframe, statusbar, position)
self.name = 'gotoGCP'
@@ -112,6 +113,7 @@
Requires MapFrame.GetFwdError, MapFrame.GetBkwError.
"""
+
def __init__(self, mapframe, statusbar, position=0):
SbTextItem.__init__(self, mapframe, statusbar, position)
self.name = 'RMSError'
Modified: grass/trunk/gui/wxpython/gcp/toolbars.py
===================================================================
--- grass/trunk/gui/wxpython/gcp/toolbars.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gcp/toolbars.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -20,7 +20,7 @@
import wx
-from core import globalvar
+from core import globalvar
from core.utils import _
from gui_core.toolbars import BaseToolbar, BaseIcons
from icons.icon import MetaIcon
@@ -31,32 +31,33 @@
:param parent: reference to GCP widget
"""
+
def __init__(self, parent):
BaseToolbar.__init__(self, parent)
-
+
self.InitToolbar(self._toolbarData())
-
+
# realize the toolbar
self.Realize()
def _toolbarData(self):
icons = {
- 'gcpAdd' : MetaIcon(img = 'gcp-add',
- label = _('Add new GCP to the list')),
- 'gcpDelete' : MetaIcon(img = 'gcp-delete',
- label = _('Delete selected GCP')),
- 'gcpClear' : MetaIcon(img = 'gcp-remove',
- label = _('Clear selected GCP')),
- 'gcpRms' : MetaIcon(img = 'gcp-rms',
- label = _('Recalculate RMS error')),
- 'georectify' : MetaIcon(img = 'georectify',
- label = _('Georectify')),
- 'gcpSave' : MetaIcon(img = 'gcp-save',
- label = _('Save GCPs to POINTS file')),
- 'gcpReload' : MetaIcon(img = 'reload',
- label = _('Reload GCPs from POINTS file')),
- }
-
+ 'gcpAdd': MetaIcon(img='gcp-add',
+ label=_('Add new GCP to the list')),
+ 'gcpDelete': MetaIcon(img='gcp-delete',
+ label=_('Delete selected GCP')),
+ 'gcpClear': MetaIcon(img='gcp-remove',
+ label=_('Clear selected GCP')),
+ 'gcpRms': MetaIcon(img='gcp-rms',
+ label=_('Recalculate RMS error')),
+ 'georectify': MetaIcon(img='georectify',
+ label=_('Georectify')),
+ 'gcpSave': MetaIcon(img='gcp-save',
+ label=_('Save GCPs to POINTS file')),
+ 'gcpReload': MetaIcon(img='reload',
+ label=_('Reload GCPs from POINTS file')),
+ }
+
return self._getToolbarData((('gcpAdd', icons["gcpAdd"],
self.parent.AddGCP),
('gcpDelete', icons["gcpDelete"],
@@ -74,48 +75,57 @@
('gcpReload', icons["gcpReload"],
self.parent.ReloadGCPs))
)
-
+
+
class GCPDisplayToolbar(BaseToolbar):
"""GCP Display toolbar
"""
+
def __init__(self, parent, toolSwitcher):
"""GCP Display toolbar constructor
"""
BaseToolbar.__init__(self, parent, toolSwitcher)
-
+
self.InitToolbar(self._toolbarData())
self._default = self.gcpset
-
+
# add tool to toggle active map window
self.togglemapid = wx.NewId()
- self.togglemap = wx.Choice(parent = self, id = self.togglemapid,
- choices = [_('source'), _('target')])
+ self.togglemap = wx.Choice(parent=self, id=self.togglemapid,
+ choices=[_('source'), _('target')])
self.InsertControl(10, self.togglemap)
- self.SetToolShortHelp(self.togglemapid, '%s %s %s' % (_('Set map canvas for '),
- BaseIcons["zoomBack"].GetLabel(),
- _(' / Zoom to map')))
+ self.SetToolShortHelp(
+ self.togglemapid, '%s %s %s' %
+ (_('Set map canvas for '),
+ BaseIcons["zoomBack"].GetLabel(),
+ _(' / Zoom to map')))
for tool in (self.gcpset, self.pan, self.zoomin, self.zoomout):
- self.toolSwitcher.AddToolToGroup(group='mouseUse', toolbar=self, tool=tool)
+ self.toolSwitcher.AddToolToGroup(
+ group='mouseUse', toolbar=self, tool=tool)
# realize the toolbar
self.Realize()
self.EnableTool(self.zoomback, False)
-
+
def _toolbarData(self):
"""Toolbar data"""
icons = {
- 'gcpSet' : MetaIcon(img = 'gcp-create',
- label = _('Update GCP coordinates'),
- desc = _('Update GCP coordinates)')),
- 'quit' : BaseIcons['quit'].SetLabel(_('Quit georectification tool')),
- 'settings' : BaseIcons['settings'].SetLabel( _('Georectifier settings')),
- 'help' : BaseIcons['help'].SetLabel(_('Georectifier manual')),
- }
-
+ 'gcpSet': MetaIcon(
+ img='gcp-create',
+ label=_('Update GCP coordinates'),
+ desc=_('Update GCP coordinates)')),
+ 'quit': BaseIcons['quit'].SetLabel(
+ _('Quit georectification tool')),
+ 'settings': BaseIcons['settings'].SetLabel(
+ _('Georectifier settings')),
+ 'help': BaseIcons['help'].SetLabel(
+ _('Georectifier manual')),
+ }
+
return self._getToolbarData((("displaymap", BaseIcons["display"],
self.parent.OnDraw),
("rendermap", BaseIcons["render"],
Modified: grass/trunk/gui/wxpython/gis_set.py
===================================================================
--- grass/trunk/gui/wxpython/gis_set.py 2016-05-03 17:11:32 UTC (rev 68373)
+++ grass/trunk/gui/wxpython/gis_set.py 2016-05-03 19:04:42 UTC (rev 68374)
@@ -50,13 +50,15 @@
exit_user_requested = 5
"""GRASS start-up screen"""
- def __init__(self, parent = None, id = wx.ID_ANY, style = wx.DEFAULT_FRAME_STYLE):
+ def __init__(self, parent=None, id=wx.ID_ANY,
+ style=wx.DEFAULT_FRAME_STYLE):
+
#
# GRASS variables
#
- self.gisbase = os.getenv("GISBASE")
- self.grassrc = self._readGisRC()
+ self.gisbase = os.getenv("GISBASE")
+ self.grassrc = self._readGisRC()
self.gisdbase = self.GetRCValue("GISDBASE")
#
@@ -65,11 +67,11 @@
self.listOfLocations = []
self.listOfMapsets = []
self.listOfMapsetsSelectable = []
-
- wx.Frame.__init__(self, parent = parent, id = id, style = style)
-
- self.locale = wx.Locale(language = wx.LANGUAGE_DEFAULT)
+ wx.Frame.__init__(self, parent=parent, id=id, style=style)
+
+ self.locale = wx.Locale(language=wx.LANGUAGE_DEFAULT)
+
# scroll panel was used here but not properly and is probably not need
# as long as it is not high too much
self.panel = wx.Panel(parent=self, id=wx.ID_ANY)
@@ -82,17 +84,23 @@
# image
try:
if os.getenv('ISISROOT'):
- name = os.path.join(globalvar.GUIDIR, "images", "startup_banner_isis.png")
+ name = os.path.join(
+ globalvar.GUIDIR,
+ "images",
+ "startup_banner_isis.png")
else:
- name = os.path.join(globalvar.GUIDIR, "images", "startup_banner.png")
+ name = os.path.join(
+ globalvar.GUIDIR, "images", "startup_banner.png")
self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY,
- wx.Bitmap(name = name,
- type = wx.BITMAP_TYPE_PNG))
+ wx.Bitmap(name=name,
+ type=wx.BITMAP_TYPE_PNG))
except:
- self.hbitmap = wx.StaticBitmap(self.panel, wx.ID_ANY, wx.BitmapFromImage(wx.EmptyImage(530,150)))
+ self.hbitmap = wx.StaticBitmap(
+ self.panel, wx.ID_ANY, wx.BitmapFromImage(
+ wx.EmptyImage(530, 150)))
# labels
- ### crashes when LOCATION doesn't exist
+ # crashes when LOCATION doesn't exist
# get version & revision
versionFile = open(os.path.join(globalvar.ETCDIR, "VERSIONNUMBER"))
versionLine = versionFile.readline().rstrip('\n')
@@ -106,14 +114,17 @@
except ValueError:
grassVersion = versionLine
grassRevisionStr = ''
-
- self.gisdbase_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
- label=" %s " % _("1. Select GRASS GIS database directory"))
- self.location_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
- label=" %s " % _("2. Select GRASS Location"))
- self.mapset_box = wx.StaticBox(parent=self.panel, id=wx.ID_ANY,
- label=" %s " % _("3. Select GRASS Mapset"))
+ self.gisdbase_box = wx.StaticBox(
+ parent=self.panel, id=wx.ID_ANY, label=" %s " %
+ _("1. Select GRASS GIS database directory"))
+ self.location_box = wx.StaticBox(
+ parent=self.panel, id=wx.ID_ANY, label=" %s " %
+ _("2. Select GRASS Location"))
+ self.mapset_box = wx.StaticBox(
+ parent=self.panel, id=wx.ID_ANY, label=" %s " %
+ _("3. Select GRASS Mapset"))
+
self.lmessage = wx.StaticText(parent=self.panel)
# It is not clear if all wx versions supports color, so try-except.
# The color itself may not be correct for all platforms/system settings
@@ -123,7 +134,7 @@
self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0))
except AttributeError:
pass
-
+
self.gisdbase_panel = wx.Panel(parent=self.panel)
self.location_panel = wx.Panel(parent=self.panel)
self.mapset_panel = wx.Panel(parent=self.panel)
@@ -156,57 +167,62 @@
pass
# buttons
- self.bstart = wx.Button(parent = self.panel, id = wx.ID_ANY,
- label = _("Start &GRASS session"))
+ self.bstart = wx.Button(parent=self.panel, id=wx.ID_ANY,
+ label=_("Start &GRASS session"))
self.bstart.SetDefault()
- self.bexit = wx.Button(parent = self.panel, id = wx.ID_EXIT)
+ self.bexit = wx.Button(parent=self.panel, id=wx.ID_EXIT)
self.bstart.SetMinSize((180, self.bexit.GetSize()[1]))
- self.bhelp = wx.Button(parent = self.panel, id = wx.ID_HELP)
- self.bbrowse = wx.Button(parent = self.gisdbase_panel, id = wx.ID_ANY,
- label = _("&Browse"))
- self.bmapset = wx.Button(parent = self.mapset_panel, id = wx.ID_ANY,
- # GTC New mapset
- label = _("&New"))
+ self.bhelp = wx.Button(parent=self.panel, id=wx.ID_HELP)
+ self.bbrowse = wx.Button(parent=self.gisdbase_panel, id=wx.ID_ANY,
+ label=_("&Browse"))
+ self.bmapset = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
+ # GTC New mapset
+ label=_("&New"))
self.bmapset.SetToolTipString(
_("Create a new Mapset in selected Location"))
- self.bwizard = wx.Button(parent = self.location_panel, id = wx.ID_ANY,
- # GTC New location
- label = _("N&ew"))
- self.bwizard.SetToolTipString(_("Create a new location using location wizard."
- " After location is created successfully,"
- " GRASS session is started."))
+ self.bwizard = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
+ # GTC New location
+ label=_("N&ew"))
+ self.bwizard.SetToolTipString(
+ _(
+ "Create a new location using location wizard."
+ " After location is created successfully,"
+ " GRASS session is started."))
self.rename_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
- # GTC Rename location
+ # GTC Rename location
label=_("Ren&ame"))
- self.rename_location_button.SetToolTipString(_("Rename selected location"))
+ self.rename_location_button.SetToolTipString(
+ _("Rename selected location"))
self.delete_location_button = wx.Button(parent=self.location_panel, id=wx.ID_ANY,
- # GTC Delete location
+ # GTC Delete location
label=_("De&lete"))
- self.delete_location_button.SetToolTipString(_("Delete selected location"))
+ self.delete_location_button.SetToolTipString(
+ _("Delete selected location"))
self.rename_mapset_button = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
- # GTC Rename mapset
- label=_("&Rename"))
+ # GTC Rename mapset
+ label=_("&Rename"))
self.rename_mapset_button.SetToolTipString(_("Rename selected mapset"))
self.delete_mapset_button = wx.Button(parent=self.mapset_panel, id=wx.ID_ANY,
- # GTC Delete mapset
+ # GTC Delete mapset
label=_("&Delete"))
self.delete_mapset_button.SetToolTipString(_("Delete selected mapset"))
# textinputs
- self.tgisdbase = wx.TextCtrl(parent = self.gisdbase_panel, id = wx.ID_ANY, value = "", size = (300, -1),
- style = wx.TE_PROCESS_ENTER)
+ self.tgisdbase = wx.TextCtrl(
+ parent=self.gisdbase_panel, id=wx.ID_ANY, value="", size=(
+ 300, -1), style=wx.TE_PROCESS_ENTER)
# Locations
- self.lblocations = GListBox(parent = self.location_panel,
+ self.lblocations = GListBox(parent=self.location_panel,
id=wx.ID_ANY, size=(180, 200),
- choices = self.listOfLocations)
+ choices=self.listOfLocations)
self.lblocations.SetColumnWidth(0, 180)
# TODO: sort; but keep PERMANENT on top of list
# Mapsets
- self.lbmapsets = GListBox(parent = self.mapset_panel,
+ self.lbmapsets = GListBox(parent=self.mapset_panel,
id=wx.ID_ANY, size=(180, 200),
- choices = self.listOfMapsets)
+ choices=self.listOfMapsets)
self.lbmapsets.SetColumnWidth(0, 180)
# layout & properties, first do layout so everything is created
@@ -214,24 +230,24 @@
self._set_properties(grassVersion, grassRevisionStr)
# events
- self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
- self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
- self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
- self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
- self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
- self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
-
+ self.bbrowse.Bind(wx.EVT_BUTTON, self.OnBrowse)
+ self.bstart.Bind(wx.EVT_BUTTON, self.OnStart)
+ self.bexit.Bind(wx.EVT_BUTTON, self.OnExit)
+ self.bhelp.Bind(wx.EVT_BUTTON, self.OnHelp)
+ self.bmapset.Bind(wx.EVT_BUTTON, self.OnCreateMapset)
+ self.bwizard.Bind(wx.EVT_BUTTON, self.OnWizard)
+
self.rename_location_button.Bind(wx.EVT_BUTTON, self.RenameLocation)
self.delete_location_button.Bind(wx.EVT_BUTTON, self.DeleteLocation)
self.rename_mapset_button.Bind(wx.EVT_BUTTON, self.RenameMapset)
self.delete_mapset_button.Bind(wx.EVT_BUTTON, self.DeleteMapset)
-
+
self.lblocations.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectLocation)
- self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
+ self.lbmapsets.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnSelectMapset)
self.lbmapsets.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnStart)
self.tgisdbase.Bind(wx.EVT_TEXT_ENTER, self.OnSetDatabase)
- self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
-
+ self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)
+
def _set_properties(self, version, revision):
"""Set frame properties"""
self.SetTitle(_("GRASS GIS %s startup%s") % (version, revision))
@@ -258,66 +274,69 @@
try:
self.tgisdbase.SetValue(self.gisdbase)
except UnicodeDecodeError:
- wx.MessageBox(parent = self, caption = _("Error"),
- message = _("Unable to set GRASS database. "
- "Check your locale settings."),
- style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-
+ wx.MessageBox(parent=self, caption=_("Error"),
+ message=_("Unable to set GRASS database. "
+ "Check your locale settings."),
+ style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
+
self.OnSetDatabase(None)
location = self.GetRCValue("LOCATION_NAME")
if location == "<UNKNOWN>":
return
if not os.path.isdir(os.path.join(self.gisdbase, location)):
location = None
-
+
# list of locations
self.UpdateLocations(self.gisdbase)
try:
self.lblocations.SetSelection(self.listOfLocations.index(location),
- force = True)
- self.lblocations.EnsureVisible(self.listOfLocations.index(location))
+ force=True)
+ self.lblocations.EnsureVisible(
+ self.listOfLocations.index(location))
except ValueError:
- sys.stderr.write(_("ERROR: Location <%s> not found\n") % self.GetRCValue("LOCATION_NAME"))
+ sys.stderr.write(
+ _("ERROR: Location <%s> not found\n") %
+ self.GetRCValue("LOCATION_NAME"))
if len(self.listOfLocations) > 0:
- self.lblocations.SetSelection(0, force = True)
+ self.lblocations.SetSelection(0, force=True)
self.lblocations.EnsureVisible(0)
location = self.listOfLocations[0]
else:
return
-
+
# list of mapsets
self.UpdateMapsets(os.path.join(self.gisdbase, location))
mapset = self.GetRCValue("MAPSET")
if mapset:
try:
self.lbmapsets.SetSelection(self.listOfMapsets.index(mapset),
- force = True)
+ force=True)
self.lbmapsets.EnsureVisible(self.listOfMapsets.index(mapset))
except ValueError:
sys.stderr.write(_("ERROR: Mapset <%s> not found\n") % mapset)
- self.lbmapsets.SetSelection(0, force = True)
+ self.lbmapsets.SetSelection(0, force=True)
self.lbmapsets.EnsureVisible(0)
-
+
def _do_layout(self):
sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer = sizer # for the layout call after changing message
- dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
-
- location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)
+ dbase_sizer = wx.BoxSizer(wx.HORIZONTAL)
- gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
- gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)
+ location_mapset_sizer = wx.BoxSizer(wx.HORIZONTAL)
- btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
-
+ gisdbase_panel_sizer = wx.BoxSizer(wx.VERTICAL)
+ gisdbase_boxsizer = wx.StaticBoxSizer(self.gisdbase_box, wx.VERTICAL)
+
+ btns_sizer = wx.BoxSizer(wx.HORIZONTAL)
+
self.gisdbase_panel.SetSizer(gisdbase_panel_sizer)
# gis data directory
-
+
gisdbase_boxsizer.Add(item=self.gisdbase_panel, proportion=1,
flag=wx.EXPAND | wx.ALL,
border=1)
-
+
gisdbase_panel_sizer.Add(item=dbase_sizer, proportion=1,
flag=wx.EXPAND | wx.ALL,
border=1)
@@ -325,12 +344,12 @@
flag=wx.EXPAND | wx.ALL,
border=1)
- dbase_sizer.Add(item = self.tgisdbase, proportion = 1,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
- border = 1)
- dbase_sizer.Add(item = self.bbrowse, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL,
- border = 1)
+ dbase_sizer.Add(item=self.tgisdbase, proportion=1,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=1)
+ dbase_sizer.Add(item=self.bbrowse, proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.ALL,
+ border=1)
gisdbase_panel_sizer.Fit(self.gisdbase_panel)
@@ -352,9 +371,11 @@
flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL,
border=1)
for button in buttons:
- buttons_sizer.Add(item=button, proportion=0,
- flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
- border=3)
+ buttons_sizer.Add(
+ item=button,
+ proportion=0,
+ flag=wx.EXPAND | wx.LEFT | wx.RIGHT | wx.BOTTOM,
+ border=3)
box_sizer.Add(item=panel, proportion=1,
flag=wx.EXPAND | wx.ALL,
border=1)
@@ -383,40 +404,40 @@
# location and mapset sizer
location_mapset_sizer.Add(item=location_boxsizer, proportion=1,
- flag = wx.LEFT | wx.RIGHT | wx.EXPAND,
- border = 3)
+ flag=wx.LEFT | wx.RIGHT | wx.EXPAND,
+ border=3)
location_mapset_sizer.Add(item=mapset_boxsizer, proportion=1,
- flag = wx.RIGHT | wx.EXPAND,
- border = 3)
+ flag=wx.RIGHT | wx.EXPAND,
+ border=3)
# buttons
- btns_sizer.Add(item = self.bstart, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL |
+ btns_sizer.Add(item=self.bstart, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL |
wx.ALIGN_CENTER_VERTICAL |
wx.ALL,
- border = 5)
- btns_sizer.Add(item = self.bexit, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL |
+ border=5)
+ btns_sizer.Add(item=self.bexit, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL |
wx.ALIGN_CENTER_VERTICAL |
wx.ALL,
- border = 5)
- btns_sizer.Add(item = self.bhelp, proportion = 0,
- flag = wx.ALIGN_CENTER_HORIZONTAL |
+ border=5)
+ btns_sizer.Add(item=self.bhelp, proportion=0,
+ flag=wx.ALIGN_CENTER_HORIZONTAL |
wx.ALIGN_CENTER_VERTICAL |
wx.ALL,
- border = 5)
-
+ border=5)
+
# main sizer
- sizer.Add(item = self.hbitmap,
- proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL |
+ sizer.Add(item=self.hbitmap,
+ proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL |
wx.ALIGN_CENTER_HORIZONTAL |
wx.ALL,
- border = 3) # image
+ border=3) # image
sizer.Add(item=gisdbase_boxsizer, proportion=0,
- flag = wx.ALIGN_CENTER_HORIZONTAL |
+ flag=wx.ALIGN_CENTER_HORIZONTAL |
wx.RIGHT | wx.LEFT | wx.TOP | wx.EXPAND,
- border = 3) # GISDBASE setting
+ border=3) # GISDBASE setting
# warning/error message
sizer.Add(item=self.lmessage,
@@ -424,13 +445,13 @@
flag=wx.ALIGN_CENTER_VERTICAL |
wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=5)
sizer.Add(item=location_mapset_sizer, proportion=1,
- flag = wx.RIGHT | wx.LEFT | wx.EXPAND,
- border = 1)
- sizer.Add(item = btns_sizer, proportion = 0,
- flag = wx.ALIGN_CENTER_VERTICAL |
+ flag=wx.RIGHT | wx.LEFT | wx.EXPAND,
+ border=1)
+ sizer.Add(item=btns_sizer, proportion=0,
+ flag=wx.ALIGN_CENTER_VERTICAL |
wx.ALIGN_CENTER_HORIZONTAL |
wx.RIGHT | wx.LEFT,
- border = 3)
+ border=3)
self.panel.SetAutoLayout(True)
self.panel.SetSizer(sizer)
@@ -442,9 +463,9 @@
"""Read variables from $HOME/.grass7/rc file
"""
grassrc = {}
-
+
gisrc = os.getenv("GISRC")
-
+
if gisrc and os.path.isfile(gisrc):
try:
rc = open(gisrc, "r")
@@ -452,12 +473,12 @@
try:
key, val = line.split(":", 1)
except ValueError as e:
- sys.stderr.write(_('Invalid line in GISRC file (%s):%s\n' % \
- (e, line)))
+ sys.stderr.write(
+ _('Invalid line in GISRC file (%s):%s\n' % (e, line)))
grassrc[key.strip()] = DecodeString(val.strip())
finally:
rc.close()
-
+
return grassrc
def _showWarning(self, text):
@@ -498,45 +519,48 @@
def GetRCValue(self, value):
"""Return GRASS variable (read from GISRC)
"""
- if self.grassrc.has_key(value):
+ if value in self.grassrc:
return self.grassrc[value]
else:
return None
-
+
def OnWizard(self, event):
"""Location wizard started"""
from location_wizard.wizard import LocationWizard
- gWizard = LocationWizard(parent = self,
- grassdatabase = self.tgisdbase.GetValue())
- if gWizard.location != None:
+ gWizard = LocationWizard(parent=self,
+ grassdatabase=self.tgisdbase.GetValue())
+ if gWizard.location is not None:
self.tgisdbase.SetValue(gWizard.grassdatabase)
self.OnSetDatabase(None)
self.UpdateMapsets(os.path.join(self.gisdbase, gWizard.location))
- self.lblocations.SetSelection(self.listOfLocations.index(gWizard.location))
+ self.lblocations.SetSelection(
+ self.listOfLocations.index(
+ gWizard.location))
self.lbmapsets.SetSelection(0)
self.SetLocation(self.gisdbase, gWizard.location, 'PERMANENT')
if gWizard.georeffile:
- message = _("Do you want to import <%(name)s> to the newly created location?") % \
- {'name': gWizard.georeffile}
- dlg = wx.MessageDialog(parent = self,
- message = message,
- caption = _("Import data?"),
- style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+ message = _("Do you want to import <%(name)s> to the newly created location?") % {
+ 'name': gWizard.georeffile}
+ dlg = wx.MessageDialog(parent=self, message=message, caption=_(
+ "Import data?"), style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
dlg.CenterOnScreen()
if dlg.ShowModal() == wx.ID_YES:
self.ImportFile(gWizard.georeffile)
else:
- self.SetDefaultRegion(location = gWizard.location)
+ self.SetDefaultRegion(location=gWizard.location)
dlg.Destroy()
else:
- self.SetDefaultRegion(location = gWizard.location)
+ self.SetDefaultRegion(location=gWizard.location)
- dlg = TextEntryDialog(parent=self,
- message=_("Do you want to create new mapset?"),
- caption=_("Create new mapset"),
- defaultValue=self._getDefaultMapsetName(),
- validator=GenericValidator(grass.legal_name, self._nameValidationFailed),
- style=wx.OK | wx.CANCEL | wx.HELP)
+ dlg = TextEntryDialog(
+ parent=self,
+ message=_("Do you want to create new mapset?"),
+ caption=_("Create new mapset"),
+ defaultValue=self._getDefaultMapsetName(),
+ validator=GenericValidator(
+ grass.legal_name,
+ self._nameValidationFailed),
+ style=wx.OK | wx.CANCEL | wx.HELP)
help = dlg.FindWindowById(wx.ID_HELP)
help.Bind(wx.EVT_BUTTON, self.OnHelp)
if dlg.ShowModal() == wx.ID_OK:
@@ -548,15 +572,14 @@
caption = _("Location <%s> created") % location
message = _("Do you want to set the default "
"region extents and resolution now?")
- dlg = wx.MessageDialog(parent = self,
- message = "%(caption)s.\n\n%(extent)s" % ({'caption': caption,
- 'extent': message}),
- caption = caption,
- style = wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
+ dlg = wx.MessageDialog(
+ parent=self, message="%(caption)s.\n\n%(extent)s" %
+ ({'caption': caption, 'extent': message}),
+ caption=caption, style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
dlg.CenterOnScreen()
if dlg.ShowModal() == wx.ID_YES:
dlg.Destroy()
- defineRegion = RegionDef(self, location = location)
+ defineRegion = RegionDef(self, location=location)
defineRegion.CenterOnScreen()
defineRegion.ShowModal()
defineRegion.Destroy()
@@ -570,71 +593,87 @@
"""
RunCommand('db.connect', flags='c')
mapName = os.path.splitext(os.path.basename(filePath))[0]
- vectors = RunCommand('v.in.ogr', input = filePath, flags = 'l',
- read = True)
-
+ vectors = RunCommand('v.in.ogr', input=filePath, flags='l',
+ read=True)
+
wx.BeginBusyCursor()
wx.Yield()
if mapName in vectors:
# vector detected
- returncode, error = RunCommand('v.in.ogr', input=filePath, output=mapName, flags='e',
- getErrorMsg=True)
+ returncode, error = RunCommand(
+ 'v.in.ogr', input=filePath, output=mapName, flags='e',
+ getErrorMsg=True)
else:
- returncode, error = RunCommand('r.in.gdal', input=filePath, output=mapName, flags='e',
- getErrorMsg=True)
+ returncode, error = RunCommand(
+ 'r.in.gdal', input=filePath, output=mapName, flags='e',
+ getErrorMsg=True)
wx.EndBusyCursor()
if returncode != 0:
- GError(parent = self,
- message = _("Import of <%(name)s> failed.\n"
- "Reason: %(msg)s") % ({'name': filePath, 'msg': error}))
+ GError(
+ parent=self,
+ message=_(
+ "Import of <%(name)s> failed.\n"
+ "Reason: %(msg)s") % ({
+ 'name': filePath,
+ 'msg': error}))
else:
- GMessage(message=_("Data file <%(name)s> imported successfully. "
- "The location's default region was set from this imported map.") %
- {'name': filePath},
- parent=self)
+ GMessage(
+ message=_(
+ "Data file <%(name)s> imported successfully. "
+ "The location's default region was set from this imported map.") % {
+ 'name': filePath},
+ parent=self)
# the event can be refactored out by using lambda in bind
def RenameMapset(self, event):
"""Rename selected mapset
"""
location = self.listOfLocations[self.lblocations.GetSelection()]
- mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
- if mapset == 'PERMANENT':
- GMessage(parent = self,
- message = _('Mapset <PERMANENT> is required for valid GRASS location.\n\n'
- 'This mapset cannot be renamed.'))
+ mapset = self.listOfMapsets[self.lbmapsets.GetSelection()]
+ if mapset == 'PERMANENT':
+ GMessage(
+ parent=self, message=_(
+ 'Mapset <PERMANENT> is required for valid GRASS location.\n\n'
+ 'This mapset cannot be renamed.'))
return
-
- dlg = TextEntryDialog(parent = self,
- message = _('Current name: %s\n\nEnter new name:') % mapset,
- caption = _('Rename selected mapset'),
- validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
-
- if dlg.ShowModal() == wx.ID_OK:
+
+ dlg = TextEntryDialog(
+ parent=self,
+ message=_('Current name: %s\n\nEnter new name:') %
+ mapset,
+ caption=_('Rename selected mapset'),
+ validator=GenericValidator(
+ grass.legal_name,
+ self._nameValidationFailed))
+
+ if dlg.ShowModal() == wx.ID_OK:
newmapset = dlg.GetValue()
- if newmapset == mapset:
+ if newmapset == mapset:
dlg.Destroy()
return
-
+
if newmapset in self.listOfMapsets:
- wx.MessageBox(parent = self,
- caption = _('Message'),
- message = _('Unable to rename mapset.\n\n'
- 'Mapset <%s> already exists in location.') % newmapset,
- style = wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
+ wx.MessageBox(
+ parent=self, caption=_('Message'), message=_(
+ 'Unable to rename mapset.\n\n'
+ 'Mapset <%s> already exists in location.') %
+ newmapset, style=wx.OK | wx.ICON_INFORMATION | wx.CENTRE)
else:
try:
os.rename(os.path.join(self.gisdbase, location, mapset),
os.path.join(self.gisdbase, location, newmapset))
self.OnSelectLocation(None)
- self.lbmapsets.SetSelection(self.listOfMapsets.index(newmapset))
- except StandardError as e:
- wx.MessageBox(parent = self,
- caption = _('Error'),
- message = _('Unable to rename mapset.\n\n%s') % e,
- style = wx.OK | wx.ICON_ERROR | wx.CENTRE)
-
+ self.lbmapsets.SetSelection(
+ self.listOfMapsets.index(newmapset))
+ except Exception as e:
+ wx.MessageBox(
+ parent=self,
+ caption=_('Error'),
+ message=_('Unable to rename mapset.\n\n%s') %
+ e,
+ style=wx.OK | wx.ICON_ERROR | wx.CENTRE)
+
dlg.Destroy()
def RenameLocation(self, event):
@@ -642,64 +681,75 @@
"""
location = self.listOfLocations[self.lblocations.GetSelection()]
- dlg = TextEntryDialog(parent = self,
- message = _('Current name: %s\n\nEnter new name:') % location,
- caption = _('Rename selected location'),
- validator = GenericValidator(grass.legal_name, self._nameValidationFailed))
+ dlg = TextEntryDialog(
+ parent=self,
+ message=_('Current name: %s\n\nEnter new name:') %
+ location,
+ caption=_('Rename selected location'),
+ validator=GenericValidator(
+ grass.legal_name,
+ self._nameValidationFailed))
- if dlg.ShowModal() == wx.ID_OK:
+ if dlg.ShowModal() == wx.ID_OK:
newlocation = dlg.GetValue()
- if newlocation == location:
+ if newlocation == location:
dlg.Destroy()
return
if newlocation in self.listOfLocations:
- wx.MessageBox(parent = self,
- caption = _('Message'),
- message = _('Unable to rename location.\n\n'
- 'Location <%s> alrea