[GRASS-SVN] r61886 - in grass/trunk/gui/wxpython: animation core gui_core lmgr mapdisp mapwin nviz rlisetup web_services
svn_grass at osgeo.org
svn_grass at osgeo.org
Fri Sep 12 15:14:55 PDT 2014
Author: lucadelu
Date: 2014-09-12 15:14:55 -0700 (Fri, 12 Sep 2014)
New Revision: 61886
Modified:
grass/trunk/gui/wxpython/animation/provider.py
grass/trunk/gui/wxpython/core/debug.py
grass/trunk/gui/wxpython/core/giface.py
grass/trunk/gui/wxpython/core/render.py
grass/trunk/gui/wxpython/gui_core/dialogs.py
grass/trunk/gui/wxpython/gui_core/gselect.py
grass/trunk/gui/wxpython/gui_core/widgets.py
grass/trunk/gui/wxpython/lmgr/giface.py
grass/trunk/gui/wxpython/mapdisp/frame.py
grass/trunk/gui/wxpython/mapwin/base.py
grass/trunk/gui/wxpython/mapwin/buffered.py
grass/trunk/gui/wxpython/mapwin/graphics.py
grass/trunk/gui/wxpython/nviz/workspace.py
grass/trunk/gui/wxpython/rlisetup/wizard.py
grass/trunk/gui/wxpython/web_services/widgets.py
Log:
wxgui: fix warning in sphinx documentation; some pep8 cleanup
Modified: grass/trunk/gui/wxpython/animation/provider.py
===================================================================
--- grass/trunk/gui/wxpython/animation/provider.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/animation/provider.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -82,9 +82,9 @@
Applies to 2D mode.
:param cmdsForComposition: list of lists of command lists
- [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp
- [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']],
- ...]
+ [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp
+ [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']],
+ ...]
:param opacities: list of opacity values
:param regions: list of regions
"""
@@ -479,7 +479,7 @@
:param region: region as a dict or None
:param bgcolor: background color as a tuple of 3 values 0 to 255
:param fileQueue: the inter process communication queue
- storing the file name of the image
+ storing the file name of the image
"""
filename = GetFileFromCmd(tempDir, cmd, region)
@@ -516,7 +516,7 @@
:param region: region as a dict
:param bgcolor: background color as a tuple of 3 values 0 to 255
:param fileQueue: the inter process communication queue
- storing the file name of the image
+ storing the file name of the image
"""
filename = GetFileFromCmd(tempDir, cmd, None)
@@ -553,7 +553,7 @@
:param opacites: list of opacities
:param bgcolor: background color as a tuple of 3 values 0 to 255
:param fileQueue: the inter process communication queue
- storing the file name of the image
+ storing the file name of the image
"""
maps = []
Modified: grass/trunk/gui/wxpython/core/debug.py
===================================================================
--- grass/trunk/gui/wxpython/core/debug.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/core/debug.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -46,7 +46,7 @@
:param level: debug level (0-5)
:param message: message to be printed
- :param *args: formatting params
+ :param args: formatting params
"""
# self.SetLevel()
if self.debuglevel > 0 and level > 0 and level <= self.debuglevel:
Modified: grass/trunk/gui/wxpython/core/giface.py
===================================================================
--- grass/trunk/gui/wxpython/core/giface.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/core/giface.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -113,6 +113,7 @@
to every GUI component.
.. note::
+
The GrassInterface process is not finished.
"""
def RunCmd(self, *args, **kwargs):
@@ -147,6 +148,7 @@
def GetLayerTree(self):
"""Returns LayerManager's tree GUI object.
.. note::
+
Will be removed from the interface.
"""
raise NotImplementedError()
@@ -160,6 +162,7 @@
"""Returns current map display.
.. note::
+
For layer related tasks use GetLayerList().
:return: MapFrame instance
@@ -171,6 +174,7 @@
"""Get list of all map displays.
.. note::
+
Might be removed from the interface.
:return: list of MapFrame instances
@@ -181,6 +185,7 @@
"""Returns current map window.
.. note::
+
For layer related tasks use GetLayerList().
"""
raise NotImplementedError()
@@ -189,6 +194,7 @@
"""Returns object which shows the progress.
.. note::
+
Some implementations may not implement this method.
"""
raise NotImplementedError()
Modified: grass/trunk/gui/wxpython/core/render.py
===================================================================
--- grass/trunk/gui/wxpython/core/render.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/core/render.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -51,20 +51,22 @@
USE_GPNMCOMP = True
+
class Layer(object):
"""Virtual class which stores information about layers (map layers and
overlays) of the map composition.
-
+
- 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):
+ def __init__(self, ltype, cmd, Map, name=None,
+ active=True, hidden=False, opacity=1.0):
"""Create new instance
-
+
.. todo::
+
pass cmd as tuple instead of list
-
+
:param ltype: layer type ('raster', 'vector', 'overlay', 'command', etc.)
:param cmd: GRASS command to render layer, given as list,
e.g. ['d.rast', 'map=elevation at PERMANENT']
@@ -74,7 +76,7 @@
:param hidden: layer is hidden, won't be listed in Layer Manager if True
:param float opacity: layer opacity <0;1>
"""
-
+
# generated file for each layer
if USE_GPNMCOMP or ltype == 'overlay':
if ltype == 'overlay':
@@ -105,48 +107,48 @@
self.cmd.append(utils.CmdToTuple(c))
else:
self.cmd = utils.CmdToTuple(cmd)
-
+
self.active = active
self.hidden = hidden
self.opacity = opacity
-
+
self.forceRender = True
-
+
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))
-
+ (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)))
-
+
def Render(self):
"""Render layer to image
-
+
:return: rendered image filename
:return: None on error or if cmdfile is defined
"""
if not self.cmd:
return None
-
+
# ignore in 2D
if self.type == '3d-raster':
return None
-
+
Debug.msg (3, "Layer.Render(): type=%s, name=%s" % \
(self.type, self.name))
-
+
# 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})
-
+
if self.mapfile:
self.environ["GRASS_PNGFILE"] = self.mapfile
-
+
# execute command
try:
if self.type == 'command':
@@ -157,7 +159,7 @@
break
if not read:
self.environ["GRASS_PNG_READ"] = "TRUE"
-
+
self.environ["GRASS_PNG_READ"] = "FALSE"
else:
ret, msg = self._runCommand(self.cmd)
@@ -166,7 +168,7 @@
if msg:
sys.stderr.write(_("Details: %s\n") % msg)
raise GException()
-
+
except GException:
# clean up after problems
for f in [self.mapfile, self.maskfile]:
@@ -176,9 +178,9 @@
f = None
self.forceRender = False
-
+
return self.mapfile
-
+
def _runCommand(self, cmd):
"""Run command to render data
"""
@@ -192,14 +194,14 @@
quiet = True,
env=self.environ,
**cmd[1])
-
+
return ret, msg
-
+
def GetCmd(self, string = False):
"""Get GRASS command as list of string.
-
+
:param string: get command as string if True otherwise as list
-
+
:return: command list/string
"""
if string:
@@ -207,7 +209,7 @@
scmd = []
for c in self.cmd:
scmd.append(utils.GetCmdString(c))
-
+
return ';'.join(scmd)
else:
return utils.GetCmdString(self.cmd)
@@ -217,17 +219,17 @@
def GetType(self):
"""Get map layer type"""
return self.type
-
+
def GetElement(self):
"""Get map element type"""
if self.type == 'raster':
return 'cell'
return self.type
-
+
def GetOpacity(self):
"""
Get layer opacity level
-
+
:return: opacity level (<0, 1>)
"""
return self.opacity
@@ -251,7 +253,7 @@
else:
return { 'name' : self.name,
'mapset' : '' }
-
+
def IsActive(self):
"""Check if layer is activated for rendering"""
return self.active
@@ -259,25 +261,25 @@
def IsHidden(self):
"""Check if layer is hidden"""
return self.hidden
-
+
def SetType(self, ltype):
"""Set layer type"""
if ltype not in utils.command2ltype.values() + ['overlay', 'command']:
raise GException(_("Unsupported map layer type '%s'") % ltype)
-
+
if ltype == 'wms' and not isinstance(self.renderMgr, RenderWMSMgr):
- self.renderMgr = RenderWMSMgr(layer=self,
- mapfile=self.mapfile,
+ self.renderMgr = RenderWMSMgr(layer=self,
+ mapfile=self.mapfile,
maskfile=self.maskfile)
elif self.type == 'wms' and ltype != 'wms':
self.renderMgr = None
-
+
self.type = ltype
def SetName(self, name):
"""Set layer name"""
self.name = name
-
+
def SetActive(self, enable = True):
"""Active or deactive layer"""
self.active = bool(enable)
@@ -292,9 +294,9 @@
value = 0.
elif value > 1:
value = 1.
-
+
self.opacity = float(value)
-
+
def SetCmd(self, cmd):
"""Set new command for layer"""
if self.type == 'command':
@@ -304,7 +306,7 @@
else:
self.cmd = utils.CmdToTuple(cmd)
Debug.msg(3, "Layer.SetCmd(): cmd='%s'" % self.GetCmd(string = True))
-
+
# for re-rendering
self.forceRender = True
@@ -332,9 +334,9 @@
class MapLayer(Layer):
def __init__(self, ltype, cmd, Map, name = None,
- active = True, hidden = False, opacity = 1.0):
+ active = True, hidden = False, opacity = 1.0):
"""Represents map layer in the map canvas
-
+
:param ltype: layer type ('raster', 'vector', 'command', etc.)
:param cmd: GRASS command to render layer,
given as list, e.g. ['d.rast',
@@ -347,26 +349,26 @@
"""
Layer.__init__(self, ltype, cmd, Map, name,
active, hidden, opacity)
-
+
def GetMapset(self):
"""Get mapset of map layer
-
+
:return: mapset name
:return: '' on error (no name given)
"""
if not self.name:
return ''
-
+
try:
return self.name.split('@')[1]
except IndexError:
return self.name
-
+
class Overlay(Layer):
def __init__(self, id, ltype, cmd, Map,
active = True, hidden = True, opacity = 1.0):
"""Represents overlay displayed in map canvas
-
+
:param id: overlay id (for PseudoDC)
:param type: overlay type ('barscale', 'legend', etc.)
:param cmd: GRASS command to render overlay,
@@ -380,11 +382,11 @@
Layer.__init__(self, 'overlay', cmd, Map, ltype,
active, hidden, opacity)
self.id = id
-
+
class Map(object):
def __init__(self, gisrc = None):
"""Map composition (stack of map layers and overlays)
-
+
:param gisrc: alternative gisrc (used eg. by georectifier)
"""
# region/extent settigns
@@ -392,24 +394,24 @@
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.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'
-
+
# setting some initial env. variables
if not self.GetWindow():
sys.stderr.write(_("Trying to recover from default region..."))
RunCommand('g.region', flags='d')
-
+
# info to report progress
self.progressInfo = None
@@ -425,14 +427,14 @@
# is some layer being downloaded?
self.downloading = False
-
+
self.layerChanged = Signal('Map.layerChanged')
self.updateProgress = Signal('Map.updateProgress')
def GetProjInfo(self):
"""Get projection info"""
return self.projinfo
-
+
def _projInfo(self):
"""Return region projection and map units information
"""
@@ -447,7 +449,7 @@
if not ret:
return projinfo
-
+
for line in ret.splitlines():
if ':' in line:
key, val = map(lambda x: x.strip(), line.split(':'))
@@ -458,9 +460,9 @@
projinfo['proj'] = 'xy'
projinfo['units'] = ''
break
-
+
return projinfo
-
+
def GetWindow(self):
"""Read WIND file and set up self.wind dictionary"""
# FIXME: duplicated region WIND == g.region (at least some values)
@@ -474,7 +476,7 @@
except IOError as 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:
@@ -482,13 +484,13 @@
except ValueError as e:
sys.stderr.write(_("\nERROR: Unable to read WIND file: %s\n") % e)
return None
-
+
self.wind[key.strip()] = value.strip()
-
+
windfile.close()
-
+
return self.wind
-
+
def AdjustRegion(self):
"""Adjusts display resolution to match monitor size in
pixels. Maintains constant display resolution, not related to
@@ -498,15 +500,15 @@
"""
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['cells'] = self.region['rows'] * self.region['cols']
-
+
Debug.msg (3, "Map.AdjustRegion(): %s" % self.region)
-
+
return self.region
def AlignResolution(self):
@@ -519,27 +521,27 @@
new = {}
n = s = e = w = 0.0
nsres = ewres = 0.0
-
+
# Get current values for region and display
reg = self.GetRegion()
nsres = reg['nsres']
ewres = reg['ewres']
-
+
n = float(self.region['n'])
s = float(self.region['s'])
e = float(self.region['e'])
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))
-
+
# Calculate new extents
new['s'] = nsres * round(s / nsres)
new['w'] = ewres * round(w / ewres)
new['n'] = new['s'] + (new['rows'] * nsres)
new['e'] = new['w'] + (new['cols'] * ewres)
-
+
return new
def AlignExtentFromDisplay(self):
@@ -550,27 +552,27 @@
res = self.region["ewres"]
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']))
-
+
ew = (self.width / 2) * res
ns = (self.height / 2) * res
-
+
self.region['n'] = self.region['center_northing'] + ns
self.region['s'] = self.region['center_northing'] - ns
self.region['e'] = self.region['center_easting'] + ew
self.region['w'] = self.region['center_easting'] - ew
-
+
# LL locations
if self.projinfo['proj'] == 'll':
self.region['n'] = min(self.region['n'], 90.0)
self.region['s'] = max(self.region['s'], -90.0)
-
+
def ChangeMapSize(self, size):
"""Change size of rendered map.
-
+
:param size: map size given as tuple
"""
try:
@@ -582,17 +584,17 @@
except ValueError:
self.width = 640
self.height = 480
-
+
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):
"""Get region settings (g.region -upgc)
-
+
Optionally extent, raster or vector map layer can be given.
-
+
:param rast: list of raster maps
:param zoom: zoom to raster map (ignore NULLs)
:param vect: list of vector maps
@@ -602,10 +604,10 @@
:param default: force default region settings
:param update: if True update current display region settings
:param add3d: add 3d region settings
-
+
:return: region settings as dictionary, e.g. {
- 'n':'4928010', 's':'4913700', 'w':'589980',...}
-
+ 'n':'4928010', 's':'4913700', 'w':'589980',...}
+
:func:`GetCurrentRegion()`
"""
region = {}
@@ -613,20 +615,20 @@
env = os.environ.copy()
if self.gisrc:
env['GISRC'] = self.gisrc
-
+
# do not update & shell style output
cmd = {}
cmd['flags'] = 'ugpc'
-
+
if default:
cmd['flags'] += 'd'
-
+
if add3d:
cmd['flags'] += '3'
-
+
if regionName:
cmd['region'] = regionName
-
+
if n:
cmd['n'] = n
if s:
@@ -635,25 +637,25 @@
cmd['e'] = e
if w:
cmd['w'] = w
-
+
if rast:
if zoom:
cmd['zoom'] = rast[0]
else:
cmd['rast'] = ','.join(rast)
-
+
if vect:
cmd['vect'] = ','.join(vect)
if rast3d:
cmd['rast3d'] = rast3d
-
+
ret, reg, msg = RunCommand('g.region',
read = True,
getErrorMsg = True,
env=env,
**cmd)
-
+
if ret != 0:
if rast:
message = _("Unable to zoom to raster map <%s>.") % rast[0] + \
@@ -670,7 +672,7 @@
"fix the problem.")
GError(message)
return self.region
-
+
for r in reg.splitlines():
key, val = r.split("=", 1)
try:
@@ -679,15 +681,15 @@
region[key] = val
Debug.msg (3, "Map.GetRegion(): %s" % region)
-
+
if update:
self.region = region
-
+
return region
def GetCurrentRegion(self):
"""Get current display region settings
-
+
:func:`GetRegion()`
"""
return self.region
@@ -695,7 +697,7 @@
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.
-
+
:param windres: uses resolution from WIND file rather than
display (for modules that require set resolution
like d.rast.num)
@@ -703,7 +705,7 @@
:return: String usable for GRASS_REGION variable or None
"""
grass_region = ""
-
+
if windres:
compRegion = self.GetRegion(add3d = windres3)
region = copy.copy(self.region)
@@ -714,15 +716,15 @@
'cols3', 'rows3', 'depths'):
if key in compRegion:
region[key] = compRegion[key]
-
+
else:
# adjust region settings to match monitor
region = self.AdjustRegion()
-
+
# read values from wind file
try:
for key in self.wind.keys():
-
+
if key == 'north':
grass_region += "north: %s; " % \
(region['n'])
@@ -779,14 +781,14 @@
(region['depths'])
else:
grass_region += key + ": " + self.wind[key] + "; "
-
+
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):
"""Returns list of layers of selected properties or list of
@@ -797,21 +799,21 @@
:param name: all layers with given name
:param active: only layers with 'active' attribute set to True or False
:param hidden: only layers with 'hidden' attribute set to True or False
-
+
:return: list of selected layers
"""
selected = []
-
+
if type(ltype) == types.StringType:
one_type = True
else:
one_type = False
-
+
if one_type and ltype == 'overlay':
llist = self.overlays
else:
llist = self.layers
-
+
# ["raster", "vector", "wms", ... ]
for layer in llist:
# specified type only
@@ -820,39 +822,39 @@
continue
elif not one_type and layer.type not in ltype:
continue
-
+
# mapset
if (mapset != None and ltype != 'overlay') and \
layer.GetMapset() != mapset:
continue
-
+
# name
if name != None and layer.name != name:
continue
-
+
# hidden and active layers
if active != None and \
hidden != None:
if layer.active == active and \
layer.hidden == hidden:
selected.append(layer)
-
+
# active layers
elif active != None:
if layer.active == active:
selected.append(layer)
-
+
# hidden layers
elif hidden != None:
if layer.hidden == hidden:
selected.append(layer)
-
+
# all layers
else:
selected.append(layer)
-
+
Debug.msg (3, "Map.GetListOfLayers(): numberof=%d" % len(selected))
-
+
return selected
def _renderLayers(self, env, force = False, overlaysOnly = False):
@@ -871,7 +873,7 @@
layers = self.overlays
else:
layers = self.layers + self.overlays
-
+
self.downloading = False
self.ReportProgress(layer=None)
@@ -881,7 +883,7 @@
# skip non-active map layers
if not layer or not layer.active:
continue
-
+
# render
if force or layer.forceRender:
layer.SetEnvironment(env)
@@ -889,42 +891,42 @@
continue
if layer.IsDownloading():
- self.downloading = True
+ self.downloading = True
self.ReportProgress(layer=layer)
# skip map layers when rendering fails
if not os.path.exists(layer.mapfile):
continue
-
+
# add image to compositing list
if layer.type != "overlay":
maps.append(layer.mapfile)
masks.append(layer.maskfile)
opacities.append(str(layer.opacity))
-
+
Debug.msg(3, "Map.Render() type=%s, layer=%s " % (layer.type, layer.name))
return maps, masks, opacities
-
+
def GetMapsMasksAndOpacities(self, force, windres, env):
"""
Used by Render function.
-
+
:return: maps, masks, opacities
"""
return self._renderLayers(force=force, env=env)
-
+
def Render(self, force = False, windres = False):
"""Creates final image composite
-
+
This function can conditionaly use high-level tools, which
should be avaliable in wxPython library
-
+
:param force: force rendering
:param windres: use region resolution (True) otherwise display
resolution
-
+
:return: name of file with rendered image or None
"""
wx.BeginBusyCursor()
@@ -941,9 +943,9 @@
env['GRASS_RENDER_IMMEDIATE'] = 'png'
else:
env['GRASS_RENDER_IMMEDIATE'] = 'cairo'
-
+
maps, masks, opacities = self.GetMapsMasksAndOpacities(force, windres, env)
-
+
# ugly hack for MSYS
if sys.platform != 'win32':
mapstr = ",".join(maps)
@@ -957,11 +959,11 @@
for item in masks:
maskstr += item.replace('\\', '/')
maskstr = maskstr.rstrip(',')
-
+
# run g.pngcomp to get composite image
bgcolor = ':'.join(map(str, UserSettings.Get(group = 'display', key = 'bgcolor',
subkey = 'color')))
-
+
if maps:
ret, msg = RunCommand('g.pnmcomp',
getErrorMsg = True,
@@ -974,25 +976,25 @@
height = self.height,
output = self.mapfile,
env=env)
-
+
if ret != 0:
print >> sys.stderr, _("ERROR: Rendering failed. Details: %s") % msg
wx.EndBusyCursor()
return None
-
+
Debug.msg (3, "Map.Render() force=%s file=%s" % (force, self.mapfile))
wx.EndBusyCursor()
if not maps:
return None
-
+
return self.mapfile
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.)
:param command: GRASS command given as list
:param name: layer name
@@ -1001,7 +1003,7 @@
:param opacity: opacity level range from 0(transparent) - 1(not transparent)
:param render: render an image if True
:param pos: position in layer list (-1 for append)
-
+
:return: new layer on success
:return: None on failure
"""
@@ -1013,51 +1015,51 @@
opacity = 1
layer = MapLayer(ltype = ltype, name = name, cmd = command, Map = self,
active = active, hidden = hidden, opacity = opacity)
-
+
# add maplayer to the list of layers
if pos > -1:
self.layers.insert(pos, layer)
else:
self.layers.append(layer)
-
+
Debug.msg (3, "Map.AddLayer(): layer=%s" % layer.name)
if render:
if not layer.Render():
raise GException(_("Unable to render map layer <%s>.") % name)
-
+
renderMgr = layer.GetRenderMgr()
if renderMgr:
renderMgr.dataFetched.connect(self.layerChanged)
renderMgr.updateProgress.connect(self.ReportProgress)
wx.EndBusyCursor()
-
+
return layer
def DeleteAllLayers(self, overlay = False):
- """Delete all layers
+ """Delete all layers
:param overlay: True to delete also overlayes
"""
self.layers = []
if overlay:
self.overlays = []
-
+
def DeleteLayer(self, layer, overlay = False):
"""Removes layer from list of layers
-
+
:param layer: layer instance in layer tree
:param overlay: delete overlay (use self.DeleteOverlay() instead)
:return: removed layer on success or None
"""
Debug.msg (3, "Map.DeleteLayer(): name=%s" % layer.name)
-
+
if overlay:
list = self.overlays
else:
list = self.layers
-
+
if layer in list:
if layer.mapfile:
base = os.path.split(layer.mapfile)[0]
@@ -1069,9 +1071,9 @@
for f in glob.glob(basefile):
os.remove(f)
list.remove(layer)
-
+
return layer
-
+
return None
def SetLayers(self, layers):
@@ -1098,29 +1100,29 @@
:param render: render an image if True
"""
Debug.msg (3, "Map.ChangeLayer(): layer=%s" % layer.name)
-
+
if 'ltype' in kargs:
layer.SetType(kargs['ltype']) # check type
-
+
if 'command' in kargs:
layer.SetCmd(kargs['command'])
-
+
if 'name' in kargs:
layer.SetName(kargs['name'])
-
+
if 'active' in kargs:
layer.SetActive(kargs['active'])
-
+
if 'hidden' in kargs:
layer.SetHidden(kargs['hidden'])
-
+
if 'opacity' in kargs:
layer.SetOpacity(kargs['opacity'])
-
+
if render and not layer.Render():
- raise GException(_("Unable to render map layer <%s>.") %
+ raise GException(_("Unable to render map layer <%s>.") %
layer.GetName())
-
+
return layer
def ChangeOpacity(self, layer, opacity):
@@ -1132,25 +1134,25 @@
# opacity must be <0;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))
def ChangeLayerActive(self, layer, active):
"""Enable or disable map layer
-
+
:param layer: layer instance in layer tree
:param active: to be rendered (True)
"""
layer.active = active
-
+
Debug.msg (3, "Map.ChangeLayerActive(): name='%s' -> active=%d" % \
(layer.name, layer.active))
def ChangeLayerName (self, layer, name):
"""Change name of the layer
-
+
:param layer: layer instance in layer tree
:param name: layer name to set up
"""
@@ -1160,9 +1162,9 @@
def RemoveLayer(self, name = None, id = None):
"""Removes layer from layer list
-
+
Layer is defined by name at mapset or id.
-
+
:param name: layer name (must be unique)
:param id: layer index in layer list def __init__(self,
targetFile, region, bandsNum, gdalDriver,
@@ -1184,15 +1186,15 @@
# del by id
elif id != None:
return self.layers.pop(id)
-
+
return None
def GetLayerIndex(self, layer, overlay = False):
"""Get index of layer in layer list.
-
+
:param layer: layer instace in layer tree
:param overlay: use list of overlays instead
-
+
:return: layer index
:return: -1 if layer not found
"""
@@ -1200,86 +1202,86 @@
list = self.overlays
else:
list = self.layers
-
+
if layer in list:
return list.index(layer)
-
+
return -1
def AddOverlay(self, id, ltype, command,
active = True, hidden = True, opacity = 1.0, render = False):
"""Adds overlay (grid, barscale, legend, etc.) to list of
overlays
-
+
:param id: overlay id (PseudoDC)
:param ltype: overlay type (barscale, legend)
:param command: GRASS command to render overlay
:param active: overlay activated (True) or disabled (False)
:param hidden: overlay is not shown in layer tree (if True)
:param render: render an image (if True)
-
+
:return: new layer on success
:return: None on failure
"""
Debug.msg (2, "Map.AddOverlay(): cmd=%s, render=%d" % (command, render))
overlay = Overlay(id = id, ltype = ltype, cmd = command, Map = self,
active = active, hidden = hidden, opacity = opacity)
-
+
# add maplayer to the list of layers
self.overlays.append(overlay)
-
+
if render and command != '' and not overlay.Render():
- raise GException(_("Unable to render overlay <%s>.") %
+ raise GException(_("Unable to render overlay <%s>.") %
ltype)
-
+
return self.overlays[-1]
def ChangeOverlay(self, id, render = False, **kargs):
"""Change overlay properities
-
+
Add new overlay if overlay with 'id' doesn't exist.
-
+
:param id: overlay id (PseudoDC)
:param ltype: overlay ltype (barscale, legend)
:param command: GRASS command to render overlay
:param active: overlay activated (True) or disabled (False)
:param hidden: overlay is not shown in layer tree (if True)
:param render: render an image (if True)
-
+
:return: new layer on success
"""
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
-
+
if 'command' in kargs:
overlay.SetCmd(kargs['command'])
-
+
if 'active' in kargs:
overlay.SetActive(kargs['active'])
-
+
if 'hidden' in kargs:
overlay.SetHidden(kargs['hidden'])
-
+
if 'opacity' in kargs:
overlay.SetOpacity(kargs['opacity'])
-
+
if render and overlay.GetCmd() != [] and not overlay.Render():
- raise GException(_("Unable to render overlay <%s>.") %
+ raise GException(_("Unable to render overlay <%s>.") %
overlay.GetType())
-
+
return overlay
- def GetOverlay(self, id, list = False):
+ def GetOverlay(self, id, list=False):
"""Return overlay(s) with 'id'
-
+
:param id: overlay id
:param list: return list of overlays of True
- otherwise suppose 'id' to be unique
-
+ otherwise suppose 'id' to be unique
+
:return: list of overlays (list=True)
:return: overlay (list=False)
:return: None (list=False) if no overlay or more overlays found
@@ -1288,20 +1290,20 @@
for overlay in self.overlays:
if overlay.id == id:
ovl.append(overlay)
-
+
if not list:
if len(ovl) != 1:
return None
else:
return ovl[0]
-
+
return ovl
def DeleteOverlay(self, overlay):
"""Delete overlay
-
+
:param overlay: overlay layer
-
+
:return: removed overlay on success or None
"""
return self.DeleteLayer(overlay, overlay = True)
@@ -1313,7 +1315,7 @@
if layer.mapfile:
try_remove(layer.mapfile)
llist.remove(layer)
-
+
def Clean(self):
"""Clean layer stack - go trough all layers and remove them
from layer list.
@@ -1322,7 +1324,7 @@
"""
self._clean(self.layers)
self._clean(self.overlays)
-
+
def ReverseListOfLayers(self):
"""Reverse list of layers"""
return self.layers.reverse()
@@ -1346,7 +1348,7 @@
self.progressInfo = {'progresVal' : 0, # current progress value
'downloading' : [], # layers, which are downloading data
'rendered' : [], # already rendered layers
- 'range' : len(self.GetListOfLayers(active = True)) +
+ 'range' : len(self.GetListOfLayers(active = True)) +
len(self.GetListOfLayers(active = True, ltype = 'overlay')) -
len(self.GetListOfLayers(active = True, ltype = '3d-raster'))}
else:
@@ -1359,7 +1361,7 @@
self.progressInfo['progresVal'] += 1
if layer in self.progressInfo['downloading']:
self.progressInfo['downloading'].remove(layer)
-
+
# for updating statusbar text
stText = ''
first = True
@@ -1372,7 +1374,7 @@
stText += '<%s>' % layer.GetName()
if stText:
stText += '...'
-
+
if self.progressInfo['range'] != len(self.progressInfo['rendered']):
if stText:
stText = _('Rendering & ') + stText
Modified: grass/trunk/gui/wxpython/gui_core/dialogs.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/dialogs.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/gui_core/dialogs.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -4,23 +4,23 @@
@brief Various dialogs used in wxGUI.
List of classes:
- - dialogs::SimpleDialog
- - dialogs::LocationDialog
- - dialogs::MapsetDialog
- - dialogs::VectorDialog
- - dialogs::NewVectorDialog
- - dialogs::SavedRegion
- - dialogs::GroupDialog
- - dialogs::MapLayersDialog
- - dialogs::ImportDialog
- - dialogs::GdalImportDialog
- - dialogs::GdalOutputDialog
- - dialogs::DxfImportDialog
- - dialogs::LayersList (used by MultiImport)
- - dialogs::SetOpacityDialog
- - dialogs::ImageSizeDialog
- - dialogs::SqlQueryFrame
- - dialogs::SymbolDialog
+ - :class:`SimpleDialog`
+ - :class:`LocationDialog`
+ - :class:`MapsetDialog`
+ - :class:`VectorDialog`
+ - :class:`NewVectorDialog`
+ - :class:`SavedRegion`
+ - :class:`GroupDialog`
+ - :class:`MapLayersDialog`
+ - :class:`ImportDialog`
+ - :class:`GdalImportDialog`
+ - :class:`GdalOutputDialog`
+ - :class:`DxfImportDialog`
+ - :class:`LayersList` (used by MultiImport)
+ - :class:`SetOpacityDialog`
+ - :class:`ImageSizeDialog`
+ - :class:`SqlQueryFrame`
+ - :class:`SymbolDialog`
(C) 2008-2011 by the GRASS Development Team
@@ -347,25 +347,26 @@
"""
if self.ftype:
return self.ftype.GetType()
-
+
return None
+
def CreateNewVector(parent, cmd, title = _('Create new vector map'),
exceptMap=None, giface=None,
disableAdd = False, disableTable = False):
"""Create new vector map layer
-
- :param cmd: (prog, **kwargs)
+
+ :param cmd: (prog, \*\*kwargs)
:param title: window title
:param exceptMap: list of maps to be excepted
:param log:
:param disableAdd: disable 'add layer' checkbox
:param disableTable: disable 'create table' checkbox
-
+
:return: dialog instance
:return: None on error
"""
- vExternalOut = grass.parse_command('v.external.out', flags = 'g')
+ vExternalOut = grass.parse_command('v.external.out', flags='g')
isNative = vExternalOut['format'] == 'native'
if cmd[0] == 'v.edit' and not isNative:
showType = True
Modified: grass/trunk/gui/wxpython/gui_core/gselect.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/gselect.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/gui_core/gselect.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -4,30 +4,30 @@
@brief Custom control that selects elements
Classes:
- - gselect::Select
- - gselect::VectorSelect
- - gselect::ListCtrlComboPopup
- - gselect::TreeCrtlComboPopup
- - gselect::VectorDBInfo
- - gselect::LayerSelect
- - gselect::DriverSelect
- - gselect::DatabaseSelect
- - gselect::TableSelect
- - gselect::ColumnSelect
- - gselect::DbaseSelect
- - gselect::LocationSelect
- - gselect::MapsetSelect
- - gselect::SubGroupSelect
- - gselect::FormatSelect
- - gselect::GdalSelect
- - gselect::ProjSelect
- - gselect::ElementSelect
- - gselect::OgrTypeSelect
- - gselect::CoordinatesSelect
- - gselect::SignatureSelect
- - gselect::SeparatorSelect
+ - :class:`Select`
+ - :class:`VectorSelect`
+ - :class:`ListCtrlComboPopup`
+ - :class:`TreeCrtlComboPopup`
+ - :class:`VectorDBInfo`
+ - :class:`LayerSelect`
+ - :class:`DriverSelect`
+ - :class:`DatabaseSelect`
+ - :class:`TableSelect`
+ - :class:`ColumnSelect`
+ - :class:`DbaseSelect`
+ - :class:`LocationSelect`
+ - :class:`MapsetSelect`
+ - :class:`SubGroupSelect`
+ - :class:`FormatSelect`
+ - :class:`GdalSelect`
+ - :class:`ProjSelect`
+ - :class:`ElementSelect`
+ - :class:`OgrTypeSelect`
+ - :class:`CoordinatesSelect`
+ - :class:`SignatureSelect`
+ - :class:`SeparatorSelect`
-(C) 2007-2014 by the GRASS Development Team
+(C) 2007-2014 by the GRASS Development Team
This program is free software under the GNU General Public License
(>=v2). Read the file COPYING that comes with GRASS for details.
@@ -69,6 +69,7 @@
from core.debug import Debug
from grass.pydispatch.signal import Signal
+
class Select(wx.combo.ComboCtrl):
def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
type = None, multiple = False, nmaps = 1,
@@ -95,7 +96,7 @@
wx.combo.ComboCtrl.__init__(self, parent=parent, id=id, size=size, validator=validator)
self.GetChildren()[0].SetName("Select")
self.GetChildren()[0].type = type
-
+
self.tcp = TreeCtrlComboPopup()
self.SetPopupControl(self.tcp)
self.SetPopupExtents(0, 100)
@@ -122,11 +123,11 @@
:param mapsets: list of acceptable mapsets (None for all in search path)
"""
self.tcp.SetData(type = type, mapsets = mapsets)
-
+
def GetElementList(self):
"""Load elements"""
self.tcp.GetElementList()
-
+
def SetType(self, etype, multiple = False, nmaps = 1,
mapsets = None, updateOnPopup = True, onPopup = None):
"""Param set element type for widget
@@ -136,23 +137,23 @@
self.tcp.SetData(type = etype, mapsets = mapsets,
multiple = multiple, nmaps = nmaps,
updateOnPopup = updateOnPopup, onPopup = onPopup)
-
+
class VectorSelect(Select):
def __init__(self, parent, ftype, **kwargs):
"""Custom to create a ComboBox with a tree control to display and
select vector maps. You can filter the vector maps. If you
don't need this feature use Select class instead
-
+
:param ftype: filter vector maps based on feature type
"""
Select.__init__(self, parent = parent, id = wx.ID_ANY,
type = 'vector', **kwargs)
-
+
self.ftype = ftype
-
+
# remove vector maps which do not contain given feature type
self.tcp.SetFilter(self._isElement)
-
+
def _isElement(self, vectorName):
"""Check if element should be filtered out"""
try:
@@ -160,16 +161,19 @@
return False
except KeyError:
return False
-
+
return True
+
class ListCtrlComboPopup(wx.combo.ComboPopup):
"""Create a list ComboBox using TreeCtrl with hidden root.
.. todo::
+
use event.EventObject instead of hardcoding (see forms.py)
- https://groups.google.com/forum/#!topic/wxpython-users/pRz6bi0k0XY
- """
+ https://groups.google.com/forum/#!topic/wxpython-users/pRz6bi0k0XY
+
+ """
# overridden ComboPopup methods
def Init(self):
self.value = [] # for multiple is False ->
@@ -266,15 +270,15 @@
root = self.seltree.AddRoot("<hidden root>")
for item in items:
self.seltree.AppendItem(root, text = item)
-
+
def OnKeyUp(self, event):
"""Enable to select items using keyboard
"""
item = self.seltree.GetSelection()
if event.GetKeyCode() == wx.WXK_DOWN:
self.seltree.SelectItem(self.seltree.GetNextVisible(item))
-
- elif event.GetKeyCode() == wx.WXK_UP:
+
+ elif event.GetKeyCode() == wx.WXK_UP:
itemPrev = self.seltree.GetPrevSibling(item)
self.seltree.SelectItem(itemPrev)
@@ -286,9 +290,9 @@
self.curitem = item
item_str = self.seltree.GetItemText(self.curitem)
if self.multiple:
- if item_str not in self.value:
+ if item_str not in self.value:
self.value.append(item_str)
- else:
+ else:
self.value = [item_str]
self.Dismiss()
@@ -309,12 +313,12 @@
item_str = self.seltree.GetItemText(self.curitem)
if self.multiple:
- if item_str not in self.value:
+ if item_str not in self.value:
self.value.append(item_str)
else:
self.value = [item_str]
self.Dismiss()
-
+
evt.Skip()
def SetData(self, **kargs):
@@ -330,7 +334,7 @@
if layer.GetType() != ltype:
continue
self.filterItems.append(layer.GetName())
-
+
def DeleteAllItems(self):
"""Delete all items in popup"""
self.seltree.DeleteAllItems()
@@ -349,14 +353,14 @@
self.onPopup = None
self.fullyQualified = True
self.extraItems = dict()
-
+
self.SetFilter(None)
self.tgis_error = False
-
+
def SetFilter(self, filter):
"""Set filter for GIS elements, see e.g. VectorSelect"""
self.filterElements = filter
-
+
def OnPopup(self, force = False):
"""Limited only for first selected"""
if not force and not self.updateOnPopup:
@@ -366,11 +370,11 @@
else:
selected = None
exclude = False
-
+
self.GetElementList(selected, exclude)
-
+
ListCtrlComboPopup.OnPopup(self, force)
-
+
def GetElementList(self, elements = None, exclude = False):
"""Get filtered list of GIS elements in accessible mapsets
and display as tree with all relevant elements displayed
@@ -379,7 +383,7 @@
# update list
self.seltree.DeleteAllItems()
self._getElementList(self.type, self.mapsets, elements, exclude)
-
+
if len(self.value) > 0:
root = self.seltree.GetRootItem()
if not root:
@@ -390,7 +394,7 @@
self.seltree.SelectItem(item)
except:
pass
-
+
def _getElementList(self, element, mapsets = None, elements = None, exclude = False):
"""Get list of GIS elements in accessible mapsets and display as tree
with all relevant elements displayed beneath each mapset branch
@@ -402,7 +406,7 @@
"""
# get current mapset
curr_mapset = grass.gisenv()['MAPSET']
-
+
# map element types to g.mlist types
elementdict = {'cell':'rast',
'raster':'rast',
@@ -453,11 +457,11 @@
'strds':'strds',
'str3ds':'str3ds',
'stvds':'stvds'}
-
+
if element not in elementdict:
self.AddItem(_('Not selectable element'), node = False)
return
-
+
if element in ('stds', 'strds', 'str3ds', 'stvds'):
if self.tgis_error is False:
import grass.temporal as tgis
@@ -471,7 +475,7 @@
else:
filesdict = grass.list_grouped(elementdict[element],
check_search_path = False)
-
+
# add extra items first
if self.extraItems:
for group, items in self.extraItems.iteritems():
@@ -480,23 +484,23 @@
for item in items:
self.AddItem(item, node = False, parent = node)
self.seltree.ExpandAllChildren(node)
-
+
# list of mapsets in current location
if mapsets is None:
mapsets = grass.mapsets(search_path = True)
-
+
# current mapset first
if curr_mapset in mapsets and mapsets[0] != curr_mapset:
mapsets.remove(curr_mapset)
mapsets.insert(0, curr_mapset)
-
+
first_mapset = None
for mapset in mapsets:
mapset_node = self.AddItem(_('Mapset') + ': ' + mapset, node = True, mapset = mapset)
node = mapset_node
if not first_mapset:
first_mapset = mapset_node
-
+
self.seltree.SetItemTextColour(mapset_node, wx.Colour(50, 50, 200))
if mapset not in filesdict:
continue
@@ -516,7 +520,7 @@
except StandardError as e:
sys.stderr.write(_("GSelect: invalid item: %s") % e)
continue
-
+
if self.seltree.ItemHasChildren(mapset_node):
sel = UserSettings.Get(group='appearance', key='elementListExpand',
subkey='selection')
@@ -535,16 +539,16 @@
pass
elif sel == 4: # expand all
collapse = False
-
+
if collapse:
self.seltree.CollapseAllChildren(mapset_node)
else:
self.seltree.ExpandAllChildren(mapset_node)
-
+
if first_mapset:
# select first mapset (MSW hack)
self.seltree.SelectItem(first_mapset)
-
+
# helpers
def _addItems(self, elist, elements, mapset, exclude, node):
"""Helper function for adding multiple items (maps, stds).
@@ -561,18 +565,18 @@
fullqElem = elem + '@' + mapset
if self.filterItems and fullqElem not in self.filterItems:
continue # skip items missed in self.filterItems
-
+
if elements is not None:
if (exclude and fullqElem in elements) or \
(not exclude and fullqElem not in elements):
continue
-
+
if self.filterElements:
if self.filterElements(fullqElem):
self.AddItem(elem, mapset = mapset, node = False, parent = node)
else:
self.AddItem(elem, mapset = mapset, node = False, parent = node)
-
+
def AddItem(self, value, mapset = None, node = True, parent = None):
if not parent:
root = self.seltree.GetRootItem()
@@ -581,19 +585,19 @@
parent = root
data = {'node': node, 'mapset': mapset}
-
+
item = self.seltree.AppendItem(parent, text = value, data = wx.TreeItemData(data))
return item
def OnKeyDown(self, event):
"""Enables to select items using keyboard"""
-
+
item = self.seltree.GetSelection()
if event.GetKeyCode() == wx.WXK_DOWN:
self.seltree.SelectItem(self.seltree.GetNextVisible(item))
-
- # problem with GetPrevVisible
- elif event.GetKeyCode() == wx.WXK_UP:
+
+ # problem with GetPrevVisible
+ elif event.GetKeyCode() == wx.WXK_UP:
if self.seltree.ItemHasChildren(item) and self.seltree.IsExpanded(self.seltree.GetPrevSibling(item)):
itemPrev = self.seltree.GetLastChild(self.seltree.GetPrevSibling(item))
else:
@@ -603,7 +607,7 @@
if item == self.seltree.GetFirstChild(self.seltree.GetRootItem())[0]:
itemPrev = item
self.seltree.SelectItem(itemPrev)
-
+
# selects first item starting with the written text in next mapset
elif event.GetKeyCode() == wx.WXK_TAB:
selected = self.seltree.GetSelection()
@@ -613,23 +617,23 @@
parent = self.seltree.GetItemParent(selected)
nextSibling = self.seltree.GetNextSibling(parent)
if wx.TreeItemId.IsOk(nextSibling):
- match = self.FindItem(nextSibling, self.GetCombo().GetValue().strip(), True)
- else:
+ match = self.FindItem(nextSibling, self.GetCombo().GetValue().strip(), True)
+ else:
match = self.FindItem(self.seltree.GetFirstChild(self.seltree.GetItemParent(parent))[0],
- self.GetCombo().GetValue().strip(), True)
+ self.GetCombo().GetValue().strip(), True)
self.seltree.SelectItem(match)
-
+
elif event.GetKeyCode() == wx.WXK_RIGHT:
if self.seltree.ItemHasChildren(item):
self.seltree.Expand(item)
-
+
elif event.GetKeyCode() == wx.WXK_LEFT:
if self.seltree.ItemHasChildren(item):
self.seltree.Collapse(item)
-
+
elif event.GetKeyCode() == wx.WXK_ESCAPE:
self.Dismiss()
-
+
elif event.GetKeyCode() == wx.WXK_RETURN:
if self.seltree.GetPyData(item)['node']:
self.value = []
@@ -637,7 +641,7 @@
fullName = self.seltree.GetItemText(item)
if self.fullyQualified and self.seltree.GetPyData(item)['mapset']:
fullName += '@' + self.seltree.GetPyData(item)['mapset']
-
+
if self.multiple:
self.value.append(fullName)
else:
@@ -648,24 +652,24 @@
self.value.append(fullName)
else:
self.value = [fullName]
-
+
self.Dismiss()
-
+
def OnLeftDown(self, evt):
"""Do the combobox selection
"""
item, flags = self.seltree.HitTest(evt.GetPosition())
if item and flags & wx.TREE_HITTEST_ONITEMLABEL:
self.curitem = item
-
+
if self.seltree.GetPyData(item)['node']:
evt.Skip()
return
-
+
fullName = self.seltree.GetItemText(item)
if self.fullyQualified and self.seltree.GetPyData(item)['mapset']:
fullName += '@' + self.seltree.GetPyData(item)['mapset']
-
+
if self.multiple:
self.value.append(fullName)
else:
@@ -676,9 +680,9 @@
self.value.append(fullName)
else:
self.value = [fullName]
-
+
self.Dismiss()
-
+
evt.Skip()
def SetData(self, **kargs):
@@ -705,7 +709,7 @@
self.fullyQualified = kargs['fullyQualified']
if 'extraItems' in kargs:
self.extraItems = kargs['extraItems']
-
+
def GetType(self):
"""Get element type
"""
@@ -721,7 +725,7 @@
self.layers = {}
# dictionary of table and associated columns (type, length, values, ids)
self.tables = {}
-
+
if not self._CheckDBConnection(): # -> self.layers
return
@@ -732,9 +736,9 @@
nuldev = file(os.devnull, 'w+')
self.layers = grass.vector_db(map = self.map, stderr = nuldev)
nuldev.close()
-
+
return bool(len(self.layers.keys()) > 0)
-
+
def _DescribeTables(self):
"""Describe linked tables"""
for layer in self.layers.keys():
@@ -764,7 +768,7 @@
'values' : [],
'ids' : []}
i += 1
-
+
# check for key column
# v.db.connect -g/p returns always key column name lowercase
if self.layers[layer]["key"] not in columns.keys():
@@ -772,11 +776,11 @@
if col.lower() == self.layers[layer]["key"]:
self.layers[layer]["key"] = col.upper()
break
-
+
self.tables[table] = columns
-
+
return True
-
+
def Reset(self):
"""Reset"""
for layer in self.layers:
@@ -784,34 +788,34 @@
for name in self.tables[table].keys():
self.tables[table][name]['values'] = []
self.tables[table][name]['ids'] = []
-
+
def GetName(self):
"""Get vector name"""
return self.map
-
+
def GetKeyColumn(self, layer):
"""Get key column of given layer
-
+
:param layer: vector layer number
"""
return str(self.layers[layer]['key'])
-
+
def GetTable(self, layer):
"""Get table name of given layer
-
+
:param layer: vector layer number
"""
return self.layers[layer]['table']
-
+
def GetDbSettings(self, layer):
"""Get database settins
:param layer: layer number
-
+
:return: (driver, database)
"""
return self.layers[layer]['driver'], self.layers[layer]['database']
-
+
def GetTableDesc(self, table):
"""Get table columns
@@ -831,14 +835,14 @@
super(LayerSelect, self).__init__(parent, id, size = size, choices = choices)
self.all = all
-
+
self.SetName("LayerSelect")
# default value
self.default = default
self.InsertLayers(vector = vector, dsn = dsn)
-
+
def InsertLayers(self, vector = None, dsn = None):
"""Insert layers for a vector into the layer combobox
@@ -857,7 +861,7 @@
dsn = dsn)
if ret:
layers = ret.splitlines()
-
+
if self.default:
if len(layers) == 0:
layers.insert(0, str(self.default))
@@ -886,55 +890,56 @@
super(DriverSelect, self).__init__(parent, id, value, pos, size,
choices, style=wx.CB_READONLY)
-
+
self.SetName("DriverSelect")
-
+
self.SetStringSelection(value)
class DatabaseSelect(wx.TextCtrl):
"""Creates combo box for selecting database driver.
"""
- def __init__(self, parent, value = '', id = wx.ID_ANY,
+ def __init__(self, parent, value = '', id = wx.ID_ANY,
size = globalvar.DIALOG_TEXTCTRL_SIZE, **kargs):
super(DatabaseSelect, self).__init__(parent, id, value, size = size, **kargs)
self.SetName("DatabaseSelect")
-
+
class TableSelect(wx.ComboBox):
"""Creates combo box for selecting attribute tables from the database
"""
def __init__(self, parent,
- id = wx.ID_ANY, value = '',
+ id = wx.ID_ANY, value = '',
size = globalvar.DIALOG_COMBOBOX_SIZE, choices = [], **kargs):
super(TableSelect, self).__init__(parent, id, value, size = size, choices = choices,
style = wx.CB_READONLY, **kargs)
self.SetName("TableSelect")
-
+
if not choices:
self.InsertTables()
-
+
def InsertTables(self, driver = None, database = None):
"""Insert attribute tables into combobox"""
items = []
if not driver or not database:
connect = grass.db_connection()
-
+
driver = connect['driver']
database = connect['database']
-
+
ret = RunCommand('db.tables',
flags = 'p',
read = True,
driver = driver,
database = database)
-
+
if ret:
for table in ret.splitlines():
items.append(table)
-
+
self.SetItems(items)
self.SetValue('')
+
class ColumnSelect(wx.combo.ComboCtrl):
"""Creates combo box for selecting columns in the attribute table
for a vector map.
@@ -945,19 +950,19 @@
:param size: window size
:param str vector: vector map name
:param layer: layer number
- :param multiple: - True if it is possible to add multiple columns
+ :param multiple: True if it is possible to add multiple columns
:param param: parameters list (see menuform.py)
- :param **kwags: wx.ComboBox parameters
+ :param kwags: wx.ComboBox parameters
"""
- def __init__(self, parent, id = wx.ID_ANY, value = '',
+ def __init__(self, parent, id = wx.ID_ANY, value = '',
size = globalvar.DIALOG_COMBOBOX_SIZE,
- vector = None, layer = 1, multiple = False,
+ vector = None, layer = 1, multiple = False,
param = None, **kwargs):
self.defaultValue = value
self.param = param
self.columns = []
- wx.combo.ComboCtrl.__init__(self, parent, id, size = size, **kwargs)
+ wx.combo.ComboCtrl.__init__(self, parent, id, size=size, **kwargs)
self.GetChildren()[0].SetName("ColumnSelect")
self.GetChildren()[0].type = type
@@ -968,14 +973,14 @@
if vector:
self.InsertColumns(vector, layer)
self.GetChildren()[0].Bind(wx.EVT_KEY_UP, self.OnKeyUp)
-
+
def GetColumns(self):
return self.columns
def OnKeyUp(self, event):
"""Shows popupwindow if down arrow key is released"""
if event.GetKeyCode() == wx.WXK_DOWN and not self.IsPopupShown():
- self.ShowPopup()
+ self.ShowPopup()
else:
event.Skip()
@@ -1021,7 +1026,7 @@
except ValueError:
pass
except (KeyError, ValueError):
- self.columns[:] = []
+ self.columns[:] = []
# update list
self.tcp.DeleteAllItems()
@@ -1029,12 +1034,12 @@
self.tcp.AddItem(col)
self.SetValue(self.defaultValue)
-
+
if self.param:
value = self.param.get('value', '')
if value != '' and value in self.columns:
self.SetValue(value)
-
+
def InsertTableColumns(self, table, driver=None, database=None):
"""Insert table columns
@@ -1043,20 +1048,20 @@
:param str database: database name
"""
self.columns[:] = []
-
+
ret = RunCommand('db.columns',
read = True,
driver = driver,
database = database,
table = table)
-
+
if ret:
self.columns = ret.splitlines()
-
+
# update list
self.tcp.DeleteAllItems()
self.SetValue(self.defaultValue)
-
+
for col in self.columns:
self.tcp.AddItem(col)
if self.param:
@@ -1073,20 +1078,20 @@
buttonText = _('Browse'),
startDirectory = grass.gisenv()['GISDBASE'],
**kwargs)
-
+
class LocationSelect(wx.ComboBox):
"""Widget for selecting GRASS location"""
- def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
+ def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
gisdbase = None, **kwargs):
- super(LocationSelect, self).__init__(parent, id, size = size,
+ super(LocationSelect, self).__init__(parent, id, size = size,
style = wx.CB_READONLY, **kwargs)
self.SetName("LocationSelect")
-
+
if not gisdbase:
self.gisdbase = grass.gisenv()['GISDBASE']
else:
self.gisdbase = gisdbase
-
+
self.SetItems(GetListOfLocations(self.gisdbase))
def UpdateItems(self, dbase):
@@ -1099,18 +1104,18 @@
self.SetItems(GetListOfLocations(self.gisdbase))
else:
self.SetItems([])
-
+
class MapsetSelect(wx.combo.ComboCtrl):
"""Widget for selecting GRASS mapset"""
- def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
+ def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
gisdbase = None, location = None, setItems = True,
searchPath = False, new = False, skipCurrent = False, multiple = False, **kwargs):
style = 0
### disabled, read-only widget has no TextCtrl children (TODO: rewrite)
### if not new and not multiple:
### style = wx.CB_READONLY
-
- wx.combo.ComboCtrl.__init__(self, parent, id, size = size,
+
+ wx.combo.ComboCtrl.__init__(self, parent, id, size = size,
style = style, **kwargs)
self.searchPath = searchPath
self.skipCurrent = skipCurrent
@@ -1119,19 +1124,19 @@
self.gisdbase = grass.gisenv()['GISDBASE']
else:
self.gisdbase = gisdbase
-
+
if not location:
self.location = grass.gisenv()['LOCATION_NAME']
else:
self.location = location
-
+
self.tcp = ListCtrlComboPopup()
self.SetPopupControl(self.tcp)
self.tcp.SetData(multiple = multiple)
-
+
if setItems:
self.tcp.SetItems(self._getMapsets())
-
+
def UpdateItems(self, location, dbase = None):
"""Update list of mapsets for given location
@@ -1142,14 +1147,14 @@
if dbase:
self.gisdbase = dbase
self.location = location
-
+
self.tcp.DeleteAllItems()
-
+
if location:
self.tcp.SetItems(self._getMapsets())
else:
self.tcp.SetItems([])
-
+
def _getMapsets(self):
if self.searchPath:
mlist = RunCommand('g.mapsets',
@@ -1158,13 +1163,13 @@
else:
mlist = GetListOfMapsets(self.gisdbase, self.location,
selectable = False)
-
+
gisenv = grass.gisenv()
if self.skipCurrent and \
gisenv['LOCATION_NAME'] == self.location and \
gisenv['MAPSET'] in mlist:
mlist.remove(gisenv['MAPSET'])
-
+
return mlist
def GetStringSelection(self):
@@ -1194,9 +1199,9 @@
class SubGroupSelect(wx.ComboBox):
"""Widget for selecting subgroups"""
- def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
+ def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
**kwargs):
- super(SubGroupSelect, self).__init__(parent, id, size = size,
+ super(SubGroupSelect, self).__init__(parent, id, size = size,
**kwargs)
self.SetName("SubGroupSelect")
@@ -1210,7 +1215,7 @@
except ValueError:
name = group
mapset = gisenv['MAPSET']
-
+
mlist = RunCommand('i.group', group=group,
read=True, flags='sg').splitlines()
try:
@@ -1220,7 +1225,7 @@
class FormatSelect(wx.Choice):
def __init__(self, parent, srcType, ogr=False,
- size=globalvar.DIALOG_SPIN_SIZE,
+ size=globalvar.DIALOG_SPIN_SIZE,
**kwargs):
"""Widget for selecting external (GDAL/OGR) format
@@ -1228,10 +1233,10 @@
:param srcType: source type ('file', 'database', 'protocol')
:param ogr: True for OGR otherwise GDAL
"""
- super(FormatSelect, self).__init__(parent, id=wx.ID_ANY, size=size,
+ super(FormatSelect, self).__init__(parent, id=wx.ID_ANY, size=size,
**kwargs)
self.SetName("FormatSelect")
-
+
if ogr:
ftype = 'ogr'
else:
@@ -1241,27 +1246,27 @@
for f in GetFormats()[ftype][srcType].values():
formats += f
self.SetItems(formats)
-
+
def GetExtension(self, name):
"""Get file extension by format name"""
formatToExt = dict()
formatToExt.update(rasterFormatExtension)
formatToExt.update(vectorFormatExtension)
-
+
return formatToExt.get(name, '')
# unused code since r47938
# wxGdalSelect, EVT_GDALSELECT = NewEvent()
class GdalSelect(wx.Panel):
- def __init__(self, parent, panel, ogr=False, link=False, dest=False,
+ def __init__(self, parent, panel, ogr=False, link=False, dest=False,
exclude=None):
"""Widget for selecting GDAL/OGR datasource, format
-
+
.. todo::
Split into GdalSelect and OgrSelect and optionally to
GdalSelectOutput, OgrSelectOutput
-
+
:param parent: parent window
:param bool ogr: use OGR selector instead of GDAL
:param bool dest: True for output (destination)
@@ -1271,7 +1276,7 @@
self.parent = parent
self.ogr = ogr
self.link = link
- self.dest = dest
+ self.dest = dest
self._sourceType = None
wx.Panel.__init__(self, parent=panel)
@@ -1283,7 +1288,7 @@
else:
settingsFile = os.path.join(GetSettingsPath(), 'wxGDAL')
- self.settsManager = ManageSettingsWidget(parent=self,
+ self.settsManager = ManageSettingsWidget(parent=self,
settingsFile=settingsFile)
self.settsManager.settingsChanged.connect(self.OnSettingsChanged)
self.settsManager.settingsSaving.connect(self.OnSettingsSaving)
@@ -1293,7 +1298,7 @@
self.inputBox.SetLabel(" %s " % _("Output settings"))
else:
self.inputBox.SetLabel(" %s " % _("Source settings"))
-
+
# source type
sources = list()
self.sourceMap = { 'file' : -1,
@@ -1335,12 +1340,12 @@
self.source.SetLabel(" %s " % _('Output type'))
else:
self.source.SetLabel(" %s " % _('Source type'))
-
+
self.source.SetSelection(0)
self.source.Bind(wx.EVT_RADIOBOX,
lambda evt: self.SetSourceType(self.sourceMapByIdx[evt.GetInt()]))
-
-
+
+
self.nativeWidgets = {}
self.fileWidgets = {}
self.dirWidgets = {}
@@ -1372,10 +1377,10 @@
fileMask += '%s (*.tar.gz;*.TAR.GZ;*.tgz;*.TGZ)|*.tar.gz;*.TAR.GZ;*.tgz;*.TGZ|' % _('TARGZ files')
# don't include last '|' - windows and mac throw error
fileMask += '%(all)s (*.*)|*.*' % {'all': _('All files')}
- # only contains formats with extensions hardcoded
+ # only contains formats with extensions hardcoded
self.filePanel = wx.Panel(parent=self)
- browse = filebrowse.FileBrowseButton(parent=self.filePanel, id=wx.ID_ANY,
+ browse = filebrowse.FileBrowseButton(parent=self.filePanel, id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText = _('File:'),
dialogTitle=_('Choose file to import'),
@@ -1388,7 +1393,7 @@
# directory
self.dirPanel = wx.Panel(parent=self)
- browse = filebrowse.DirBrowseButton(parent=self.dirPanel, id=wx.ID_ANY,
+ browse = filebrowse.DirBrowseButton(parent=self.dirPanel, id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText=_('Directory:'),
dialogTitle=_('Choose input directory'),
@@ -1427,7 +1432,7 @@
dbChoice.Bind(wx.EVT_CHOICE, lambda evt: self.SetDatabase(db=dbChoice.GetStringSelection()))
self.dbWidgets['format'] = dbChoice
- browse = filebrowse.FileBrowseButton(parent=self.dbPanel, id=wx.ID_ANY,
+ browse = filebrowse.FileBrowseButton(parent=self.dbPanel, id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText=_("Name:"),
dialogTitle=_('Choose file'),
@@ -1441,7 +1446,7 @@
self.dbWidgets['text'].Bind(wx.EVT_TEXT, self.OnUpdate)
self.dbWidgets['textLabel1'] = wx.StaticText(parent=self.dbPanel, label=_("Name:"))
self.dbWidgets['textLabel2'] = wx.StaticText(parent=self.dbPanel, label=_("Name:"))
- self.dbWidgets['featType'] = wx.RadioBox(parent=self.dbPanel, id=wx.ID_ANY,
+ self.dbWidgets['featType'] = wx.RadioBox(parent=self.dbPanel, id=wx.ID_ANY,
label = " %s " % _("Feature type:"),
choices = [_("simple features"), _("topological")],
majorDimension=2,
@@ -1450,7 +1455,7 @@
self.dbWidgets['featType'].Disable()
else:
self.dbWidgets['featType'].Hide()
- browse = filebrowse.DirBrowseButton(parent=self.dbPanel, id=wx.ID_ANY,
+ browse = filebrowse.DirBrowseButton(parent=self.dbPanel, id=wx.ID_ANY,
size=globalvar.DIALOG_GSELECT_SIZE,
labelText=_('Directory:'),
dialogTitle=_('Choose input directory'),
@@ -1464,10 +1469,10 @@
self.protocolPanel = wx.Panel(parent=self)
protocolFormats = GetFormats(writableOnly=self.dest)[fType]['protocol']
protocolChoice = wx.Choice(parent=self.protocolPanel, choices=protocolFormats)
- self.protocolWidgets['format'] = protocolChoice
+ self.protocolWidgets['format'] = protocolChoice
- self.protocolWidgets['text'] = wx.TextCtrl(parent=self.protocolPanel)
- self.protocolWidgets['text'].Bind(wx.EVT_TEXT, self.OnUpdate)
+ self.protocolWidgets['text'] = wx.TextCtrl(parent=self.protocolPanel)
+ self.protocolWidgets['text'].Bind(wx.EVT_TEXT, self.OnUpdate)
self.protocolWidgets['options'] = wx.TextCtrl(parent=self.protocolPanel)
# native
@@ -1511,7 +1516,7 @@
else:
dsn = data.get('dsn')
options = data.get('options', '')
-
+
self.SetSourceType(sourceType)
self.source.SetSelection(self.sourceMap[sourceType])
@@ -1577,7 +1582,7 @@
pos=(0, 3))
sizer.Add(item=self.dirWidgets['browse'],
flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
- pos=(1, 0), span=(1, 4))
+ pos=(1, 0), span=(1, 4))
if self.dest:
sizer.Add(item=wx.StaticText(parent=self.dirPanel,
label = _("Creation options:")),
@@ -1637,13 +1642,13 @@
sizer.Add(item=self.dbWidgets['options'],
flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
pos=(5, 1), span=(1, 2))
-
+
# help button
helpBtn = wx.Button(parent=self.dbPanel, id=wx.ID_HELP)
helpBtn.Bind(wx.EVT_BUTTON, self.OnHelp)
sizer.Add(item=helpBtn,
pos=(5, 3))
-
+
else:
self.dbWidgets['options'].Hide()
@@ -1691,10 +1696,10 @@
for panel in (self.nativePanel, self.filePanel,
self.dirPanel, self.dbPanel,
self.protocolPanel):
-
+
self.changingSizer.Add(item=panel, proportion=1,
flag=wx.EXPAND)
-
+
mainSizer.Add(item=self.settsManager, proportion=0,
flag=wx.ALL | wx.EXPAND, border=5)
mainSizer.Add(item=self.source, proportion=0,
@@ -1711,7 +1716,7 @@
formatToExt.update(rasterFormatExtension)
formatToExt.update(vectorFormatExtension)
- return formatToExt.get(name, '')
+ return formatToExt.get(name, '')
def SetSourceType(self, sourceType):
"""Set source type (db, file, dir, ...).
@@ -1728,7 +1733,7 @@
if sourceType == 'db':
self.dbWidgets['format'].SetItems(self.dbFormats)
if self.dbFormats:
- if 'PostgreSQL' in self.dbFormats:
+ if 'PostgreSQL' in self.dbFormats:
self.dbWidgets['format'].SetStringSelection('PostgreSQL')
else:
self.dbWidgets['format'].SetSelection(0)
@@ -1748,9 +1753,9 @@
if len(data) == 3:
data.append('')
elif len < 3:
- return
+ return
- self.source.SetSelection(self.sourceMap[data[0]])
+ self.source.SetSelection(self.sourceMap[data[0]])
self.SetSourceType(data[0])
if data[0] == 'file':
self.fileWidgets['browse'].SetValue(data[1])
@@ -1777,7 +1782,7 @@
else:
self.dbWidgets[name].SetValue(data[1])
self.dbWidgets['options'].SetValue(data[3])
-
+
if not self.dest:
self.reloadDataRequired.emit(data=None)
self._reloadLayers()
@@ -1854,7 +1859,7 @@
'PostGIS Raster driver')
enableFeatType = self.dest and self.ogr and db in ('PostgreSQL')
showText = not(showBrowse or showChoice or showDirbrowse)
-
+
sizer.Show(self.dbWidgets['browse'], show=showBrowse)
sizer.Show(self.dbWidgets['dirbrowse'], show=showDirbrowse)
sizer.Show(self.dbWidgets['choice'], show=showChoice)
@@ -1903,7 +1908,7 @@
if not dsn:
return
- data = list()
+ data = list()
layerId = 1
if self.ogr:
@@ -1941,7 +1946,7 @@
# unused code since r47938
# if self.ogr:
# dsn += '@OGR'
-#
+#
# evt = wxGdalSelect(dsn = dsn)
# evt.SetId(self.input[self.dsnType][1].GetId())
# wx.PostEvent(self.parent, evt)
@@ -1994,7 +1999,7 @@
else:
options = ''
options += self.dbWidgets['options'].GetValue()
-
+
return options.strip()
def OnHelp(self, event):
@@ -2016,7 +2021,7 @@
cmd = 'v.in.ogr'
else:
cmd = 'r.in.gdal'
-
+
RunCommand('g.manual', entry = cmd)
class ProjSelect(wx.ComboBox):
@@ -2024,14 +2029,14 @@
r.proj/v.proj modules."""
def __init__(self, parent, isRaster, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
**kwargs):
- super(ProjSelect, self).__init__(parent, id, size = size,
+ super(ProjSelect, self).__init__(parent, id, size = size,
style = wx.CB_READONLY, **kwargs)
self.SetName("ProjSelect")
self.isRaster = isRaster
-
+
def UpdateItems(self, dbase, location, mapset):
"""Update list of maps
-
+
"""
if not dbase:
dbase = grass.gisenv()['GISDBASE']
@@ -2058,26 +2063,26 @@
for line in ret.splitlines():
listMaps.append(line.strip())
ListSortLower(listMaps)
-
+
self.SetItems(listMaps)
self.SetValue('')
class ElementSelect(wx.Choice):
- def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
+ def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_COMBOBOX_SIZE,
**kwargs):
"""Widget for selecting GIS element
-
+
:param parent: parent window
"""
- super(ElementSelect, self).__init__(parent, id, size = size,
+ super(ElementSelect, self).__init__(parent, id, size = size,
**kwargs)
self.SetName("ElementSelect")
-
+
task = gtask.parse_interface('g.list')
p = task.get_param(value = 'type')
self.values = p.get('values', [])
self.valuesDesc = p.get('values_desc', [])
-
+
self.SetItems(self.valuesDesc)
def GetValue(self, name):
@@ -2098,7 +2103,7 @@
:param panel: wx.Panel instance used as parent window
"""
wx.Panel.__init__(self, parent = panel, id = wx.ID_ANY)
-
+
self.ftype = wx.Choice(parent = self, id = wx.ID_ANY,
size = (200, -1),
choices = (_("Point"), _("LineString"), _("Polygon")))
@@ -2116,7 +2121,7 @@
sizer.Add(item = self.ftype,
proportion = 0,
flag = wx.EXPAND | wx.ALIGN_RIGHT)
-
+
self.SetSizer(sizer)
sizer.Fit(self)
@@ -2136,7 +2141,7 @@
class CoordinatesSelect(wx.Panel):
def __init__(self, parent, giface, multiple = False, **kwargs):
"""Widget to get coordinates from map window by mouse click
-
+
:param parent: parent window
:param giface: GRASS interface
:param multiple: - True if it is possible to insert more coordinates
@@ -2147,11 +2152,11 @@
self.drawMapWin = None
super(CoordinatesSelect, self).__init__(parent=parent, id=wx.ID_ANY)
-
- self.coordsField = wx.TextCtrl(parent=self, id=wx.ID_ANY,
+
+ self.coordsField = wx.TextCtrl(parent=self, id=wx.ID_ANY,
size=globalvar.DIALOG_TEXTCTRL_SIZE,
validator=CoordinatesValidator())
-
+
icon = wx.Bitmap(os.path.join(globalvar.ICONDIR, "grass", "pointer.png"))
self.buttonInsCoords = buttons.ThemedGenBitmapToggleButton(parent=self, id=wx.ID_ANY,
bitmap=icon,
@@ -2163,19 +2168,19 @@
if mapdisp:
switcher = mapdisp.GetToolSwitcher()
switcher.AddCustomToolToGroup(group='mouseUse',
- btnId=self.buttonInsCoords.GetId(),
+ btnId=self.buttonInsCoords.GetId(),
toggleHandler=self.buttonInsCoords.SetValue)
self._doLayout()
self.coordsField.Bind(wx.EVT_TEXT, lambda event : self._draw(delay=1))
-
+
def _doLayout(self):
self.dialogSizer = wx.BoxSizer(wx.HORIZONTAL)
- self.dialogSizer.Add(item = self.coordsField,
- proportion = 1,
+ self.dialogSizer.Add(item = self.coordsField,
+ proportion = 1,
flag = wx.EXPAND)
self.dialogSizer.Add(item = self.buttonInsCoords)
self.SetSizer(self.dialogSizer)
-
+
def _onClick(self, event):
"""Button for interacitve inserting of coordinates clicked"""
@@ -2183,16 +2188,16 @@
if self.buttonInsCoords.GetToggle() and self.mapWin:
switcher = self._giface.GetMapDisplay().GetToolSwitcher()
switcher.ToolChanged(self.buttonInsCoords.GetId())
- if self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
+ if self.mapWin.RegisterMouseEventHandler(wx.EVT_LEFT_DOWN,
self._onMapClickHandler,
'cross') == False:
return
-
+
self.registered = True
self._giface.GetMapDisplay().Raise()
else:
if self.mapWin and \
- self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
+ self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
self._onMapClickHandler):
self.registered = False
return
@@ -2213,7 +2218,7 @@
items = self.pointsToDraw.GetAllItems()
for i in items:
self.pointsToDraw.DeleteItem(i)
-
+
coords = self._getCoords()
if coords is not None:
for i in range(len(coords)/2):
@@ -2225,7 +2230,7 @@
def _getCoords(self):
"""Get list of coordinates.
- :return: None if values are not valid
+ :return: None if values are not valid
"""
if self.coordsField.GetValidator().Validate():
return self.coordsField.GetValue().split(',')
@@ -2236,10 +2241,10 @@
"""Gets coordinates from mapwindow"""
if event == "unregistered":
return
-
+
e, n = self.mapWin.GetLastEN()
prevCoords = ""
-
+
if self.multiple:
prevCoords = self.coordsField.GetValue().strip()
if prevCoords != "":
@@ -2254,14 +2259,14 @@
"""Unregistrates _onMapClickHandler from mapWin"""
self.drawCleanUp()
self._giface.updateMap.emit(render=False, renderVector=False)
-
+
mapdisp = self._giface.GetMapDisplay()
if mapdisp:
switcher = mapdisp.GetToolSwitcher()
switcher.RemoveCustomToolFromGroup(self.buttonInsCoords.GetId())
-
+
if self.mapWin and self.registered:
- self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
+ self.mapWin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN,
self._onMapClickHandler)
def GetTextWin(self):
@@ -2270,9 +2275,9 @@
class SignatureSelect(wx.ComboBox):
"""Widget for selecting signatures"""
- def __init__(self, parent, element, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
+ def __init__(self, parent, element, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
**kwargs):
- super(SignatureSelect, self).__init__(parent, id, size = size,
+ super(SignatureSelect, self).__init__(parent, id, size = size,
**kwargs)
self.element = element
self.SetName("SignatureSelect")
@@ -2291,10 +2296,10 @@
except ValueError:
name = group
mapset = gisenv['MAPSET']
-
+
path = os.path.join(gisenv['GISDBASE'], gisenv['LOCATION_NAME'], mapset,
'group', name)
-
+
if subgroup:
path = os.path.join(path, 'subgroup', subgroup)
try:
@@ -2308,9 +2313,9 @@
class SeparatorSelect(wx.ComboBox):
"""Widget for selecting seperator"""
- def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
+ def __init__(self, parent, id = wx.ID_ANY, size = globalvar.DIALOG_GSELECT_SIZE,
**kwargs):
- super(SeparatorSelect, self).__init__(parent, id, size = size,
+ super(SeparatorSelect, self).__init__(parent, id, size = size,
**kwargs)
self.SetName("SeparatorSelect")
self.SetItems(['pipe', 'comma', 'space', 'tab', 'newline'])
Modified: grass/trunk/gui/wxpython/gui_core/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/gui_core/widgets.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/gui_core/widgets.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -83,7 +83,7 @@
and other methods can be delegated by @c __getattr__.
"""
def __init__(self, classObject, widget):
- """
+ """
:param classObject: notebook class name (object, i.e. FlatNotebook)
:param widget: notebook instance
"""
@@ -148,7 +148,7 @@
"""Set active notebook page.
:param page: name, eg. 'layers', 'output', 'search', 'pyshell', 'nviz'
- (depends on concrete notebook instance)
+ (depends on concrete notebook instance)
"""
idx = self.GetPageIndexByName(page)
if self.classObject.GetSelection(self.widget) != idx:
@@ -174,7 +174,7 @@
def GetPageIndexByName(self, page):
"""Get notebook page index
-
+
:param page: name
"""
if page not in self.notebookPages:
@@ -187,7 +187,7 @@
def HighlightPageByName(self, page):
pageIndex = self.GetPageIndexByName(page)
self.HighlightPage(pageIndex)
-
+
def HighlightPage(self, index):
if self.classObject.GetSelection(self.widget) != index:
text = self.classObject.GetPageText(self.widget, index)
@@ -215,12 +215,12 @@
def GetPageIndexByName(self, page):
"""Get notebook page index
-
+
:param page: name
"""
if page not in self.notebookPages:
return -1
-
+
return self.classObject.GetPageIndex(self.widget, self.notebookPages[page])
@@ -232,12 +232,15 @@
"""
def __init__(self, parent, style, **kwargs):
if globalvar.hasAgw:
- FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, agwStyle = style, **kwargs)
+ FN.FlatNotebook.__init__(self, parent, id=wx.ID_ANY,
+ agwStyle=style, **kwargs)
else:
- FN.FlatNotebook.__init__(self, parent, id = wx.ID_ANY, style = style, **kwargs)
-
- self.controller = FlatNotebookController(classObject = FN.FlatNotebook, widget = self)
+ FN.FlatNotebook.__init__(self, parent, id=wx.ID_ANY,
+ style=style, **kwargs)
+ self.controller = FlatNotebookController(classObject=FN.FlatNotebook,
+ widget=self)
+
def AddPage(self, **kwargs):
"""@copydoc NotebookController::AddPage()"""
self.controller.AddPage(**kwargs)
@@ -261,14 +264,16 @@
def __getattr__(self, name):
return getattr(self.controller, name)
+
class FormNotebook(wx.Notebook):
"""Notebook widget.
Respects native look.
"""
def __init__(self, parent, style):
- wx.Notebook.__init__(self, parent, id = wx.ID_ANY, style = style)
- self.controller = NotebookController(classObject = wx.Notebook, widget = self)
+ wx.Notebook.__init__(self, parent, id=wx.ID_ANY, style=style)
+ self.controller = NotebookController(classObject=wx.Notebook,
+ widget=self)
def AddPage(self, **kwargs):
"""@copydoc NotebookController::AddPage()"""
@@ -300,9 +305,10 @@
Respects native look.
"""
def __init__(self, parent, style):
- wx.Listbook.__init__(self, parent, id = wx.ID_ANY, style = style)
- self.controller = NotebookController(classObject = wx.Listbook, widget = self)
-
+ wx.Listbook.__init__(self, parent, id=wx.ID_ANY, style=style)
+ self.controller = NotebookController(classObject=wx.Listbook,
+ widget=self)
+
def AddPage(self, **kwargs):
"""@copydoc NotebookController::AddPage()"""
self.controller.AddPage(**kwargs)
@@ -329,23 +335,25 @@
class ScrolledPanel(SP.ScrolledPanel):
"""Custom ScrolledPanel to avoid strange behaviour concerning focus"""
- def __init__(self, parent, style = wx.TAB_TRAVERSAL):
- SP.ScrolledPanel.__init__(self, parent = parent, id = wx.ID_ANY, style = style)
+ def __init__(self, parent, style=wx.TAB_TRAVERSAL):
+ SP.ScrolledPanel.__init__(self, parent=parent, id=wx.ID_ANY,
+ style=style)
def OnChildFocus(self, event):
pass
-
+
+
class NumTextCtrl(wx.TextCtrl):
"""Class derived from wx.TextCtrl for numerical values only"""
def __init__(self, parent, **kwargs):
## self.precision = kwargs.pop('prec')
- wx.TextCtrl.__init__(self, parent = parent,
- validator = NTCValidator(flag = 'DIGIT_ONLY'), **kwargs)
-
-
+ wx.TextCtrl.__init__(self, parent=parent,
+ validator=NTCValidator(flag='DIGIT_ONLY'),
+ **kwargs)
+
def SetValue(self, value):
- super(NumTextCtrl, self).SetValue( str(value))
-
+ super(NumTextCtrl, self).SetValue(str(value))
+
def GetValue(self):
val = super(NumTextCtrl, self).GetValue()
if val == '':
@@ -355,10 +363,11 @@
except ValueError:
val = ''.join(''.join(val.split('-')).split('.'))
return float(val)
-
+
def SetRange(self, min, max):
pass
-
+
+
class FloatSlider(wx.Slider):
"""Class derived from wx.Slider for floats"""
def __init__(self, **kwargs):
@@ -368,18 +377,19 @@
#init range
self.minValueOrig = 0
self.maxValueOrig = 1
-
+
def SetValue(self, value):
- value *= self.coef
+ value *= self.coef
if abs(value) < 1 and value != 0:
while abs(value) < 1:
value *= 100
self.coef *= 100
- super(FloatSlider, self).SetRange(self.minValueOrig * self.coef, self.maxValueOrig * self.coef)
+ super(FloatSlider, self).SetRange(self.minValueOrig * self.coef,
+ self.maxValueOrig * self.coef)
super(FloatSlider, self).SetValue(value)
-
+
Debug.msg(4, "FloatSlider.SetValue(): value = %f" % value)
-
+
def SetRange(self, minValue, maxValue):
self.coef = 1.
self.minValueOrig = minValue
@@ -392,32 +402,33 @@
super(FloatSlider, self).SetValue(super(FloatSlider, self).GetValue() * self.coef)
super(FloatSlider, self).SetRange(minValue, maxValue)
Debug.msg(4, "FloatSlider.SetRange(): minValue = %f, maxValue = %f" % (minValue, maxValue))
-
+
def GetValue(self):
val = super(FloatSlider, self).GetValue()
Debug.msg(4, "FloatSlider.GetValue(): value = %f" % (val/self.coef))
return val/self.coef
-
-
+
+
class SymbolButton(BitmapTextButton):
"""Button with symbol and label."""
def __init__(self, parent, usage, label, **kwargs):
"""Constructor
-
+
:param parent: parent (usually wx.Panel)
:param usage: determines usage and picture
:param label: displayed label
"""
size = (15, 15)
buffer = wx.EmptyBitmap(*size)
- BitmapTextButton.__init__(self, parent = parent, label = " " + label, bitmap = buffer, **kwargs)
-
+ BitmapTextButton.__init__(self, parent=parent, label=" " + label,
+ bitmap=buffer, **kwargs)
+
dc = wx.MemoryDC()
dc.SelectObject(buffer)
maskColor = wx.Colour(255, 255, 255)
dc.SetBrush(wx.Brush(maskColor))
dc.Clear()
-
+
if usage == 'record':
self.DrawRecord(dc, size)
elif usage == 'stop':
@@ -431,23 +442,24 @@
buffer.SetMaskColour(maskColor)
self.SetBitmapLabel(buffer)
dc.SelectObject(wx.NullBitmap)
-
+
def DrawRecord(self, dc, size):
"""Draw record symbol"""
dc.SetBrush(wx.Brush(wx.Colour(255, 0, 0)))
dc.DrawCircle(size[0]/2, size[1] / 2, size[0] / 2)
-
+
def DrawStop(self, dc, size):
"""Draw stop symbol"""
dc.SetBrush(wx.Brush(wx.Colour(50, 50, 50)))
dc.DrawRectangle(0, 0, size[0], size[1])
-
+
def DrawPlay(self, dc, size):
"""Draw play symbol"""
dc.SetBrush(wx.Brush(wx.Colour(0, 255, 0)))
- points = (wx.Point(0, 0), wx.Point(0, size[1]), wx.Point(size[0], size[1] / 2))
+ points = (wx.Point(0, 0), wx.Point(0, size[1]), wx.Point(size[0],
+ size[1] / 2))
dc.DrawPolygon(points)
-
+
def DrawPause(self, dc, size):
"""Draw pause symbol"""
dc.SetBrush(wx.Brush(wx.Colour(50, 50, 50)))
@@ -486,7 +498,8 @@
"""Calculates size of wrapped label"""
parent = self.GetParent()
newLabel = wordwrap(text=self._initialLabel, width=parent.GetSize()[0],
- dc=wx.ClientDC(parent), breakLongWords=True, margin=self._margin)
+ dc=wx.ClientDC(parent), breakLongWords=True,
+ margin=self._margin)
GenStaticText.SetLabel(self, newLabel)
def SetLabel(self, label):
@@ -497,15 +510,15 @@
class BaseValidator(wx.PyValidator):
def __init__(self):
wx.PyValidator.__init__(self)
-
- self.Bind(wx.EVT_TEXT, self.OnText)
+ self.Bind(wx.EVT_TEXT, self.OnText)
+
def OnText(self, event):
"""Do validation"""
self.Validate()
-
+
event.Skip()
-
+
def Validate(self):
"""Validate input"""
textCtrl = self.GetWindow()
@@ -517,7 +530,7 @@
except ValueError:
self._notvalid()
return False
-
+
self._valid()
return True
@@ -533,16 +546,17 @@
sysColor = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
textCtrl.SetBackgroundColour(sysColor)
-
+
textCtrl.Refresh()
return True
def TransferToWindow(self):
return True # Prevent wxDialog from complaining.
-
+
def TransferFromWindow(self):
return True # Prevent wxDialog from complaining.
+
class CoordinatesValidator(BaseValidator):
"""Validator for coordinates input (list of floats separated by comma)"""
@@ -557,17 +571,17 @@
if text:
try:
text = text.split(',')
-
+
for t in text:
float(t)
- if len(text)%2 != 0:
+ if len(text) % 2 != 0:
return False
except ValueError:
self._notvalid()
return False
-
+
self._valid()
return True
@@ -575,31 +589,34 @@
"""Clone validator"""
return CoordinatesValidator()
+
class IntegerValidator(BaseValidator):
"""Validator for floating-point input"""
def __init__(self):
BaseValidator.__init__(self)
self.type = int
-
+
def Clone(self):
"""Clone validator"""
return IntegerValidator()
+
class FloatValidator(BaseValidator):
"""Validator for floating-point input"""
def __init__(self):
BaseValidator.__init__(self)
self.type = float
-
+
def Clone(self):
"""Clone validator"""
return FloatValidator()
+
class EmailValidator(BaseValidator):
"""Validator for email input"""
def __init__(self):
BaseValidator.__init__(self)
-
+
def Validate(self):
"""Validate input"""
textCtrl = self.GetWindow()
@@ -608,19 +625,20 @@
if re.match(r'\b[\w.-]+@[\w.-]+.\w{2,4}\b', text) is None:
self._notvalid()
return False
-
+
self._valid()
return True
-
+
def Clone(self):
"""Clone validator"""
return EmailValidator()
-
+
+
class TimeISOValidator(BaseValidator):
"""Validator for time ISO format (YYYY-MM-DD) input"""
def __init__(self):
BaseValidator.__init__(self)
-
+
def Validate(self):
"""Validate input"""
textCtrl = self.GetWindow()
@@ -631,17 +649,18 @@
except:
self._notvalid()
return False
-
+
self._valid()
return True
-
+
def Clone(self):
"""Clone validator"""
return TimeISOValidator()
+
class NTCValidator(wx.PyValidator):
"""validates input in textctrls, taken from wxpython demo"""
- def __init__(self, flag = None):
+ def __init__(self, flag=None):
wx.PyValidator.__init__(self)
self.flag = flag
self.Bind(wx.EVT_CHAR, self.OnChar)
@@ -661,8 +680,9 @@
wx.Bell()
# Returning without calling even.Skip eats the event before it
# gets to the text control
- return
+ return
+
class SimpleValidator(wx.PyValidator):
"""This validator is used to ensure that the user has entered something
into the text object editor dialog's text field.
@@ -700,7 +720,6 @@
"""
return True # Prevent wxDialog from complaining.
-
def TransferFromWindow(self):
"""Transfer data from window to validator.
@@ -748,7 +767,6 @@
"""
return True # Prevent wxDialog from complaining.
-
def TransferFromWindow(self):
"""Transfer data from window to validator.
"""
@@ -757,13 +775,13 @@
class SingleSymbolPanel(wx.Panel):
"""Panel for displaying one symbol.
-
+
Changes background when selected. Assumes that parent will catch
events emitted on mouse click. Used in gui_core::dialog::SymbolDialog.
"""
def __init__(self, parent, symbolPath):
"""Panel constructor
-
+
Signal symbolSelectionChanged - symbol selected
- attribute 'name' (symbol name)
- attribute 'doubleClick' (underlying cause)
@@ -773,63 +791,64 @@
"""
self.symbolSelectionChanged = Signal('SingleSymbolPanel.symbolSelectionChanged')
- wx.Panel.__init__(self, parent, id = wx.ID_ANY, style = wx.BORDER_RAISED)
+ wx.Panel.__init__(self, parent, id=wx.ID_ANY, style=wx.BORDER_RAISED)
self.SetName(os.path.splitext(os.path.basename(symbolPath))[0])
self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.Bitmap(symbolPath))
self.selected = False
self.selectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT)
self.deselectColor = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW)
-
+
sizer = wx.BoxSizer()
- sizer.Add(item = self.sBmp, proportion = 0, flag = wx.ALL | wx.ALIGN_CENTER, border = 5)
+ sizer.Add(item = self.sBmp, proportion=0, flag=wx.ALL | wx.ALIGN_CENTER, border = 5)
self.SetBackgroundColour(self.deselectColor)
self.SetMinSize(self.GetBestSize())
self.SetSizerAndFit(sizer)
-
+
# binding to both (staticBitmap, Panel) necessary
self.sBmp.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
self.sBmp.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
-
+
def OnLeftDown(self, event):
"""Panel selected, background changes"""
self.selected = True
self.SetBackgroundColour(self.selectColor)
self.Refresh()
event.Skip()
-
+
self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=False)
-
+
def OnDoubleClick(self, event):
self.symbolSelectionChanged.emit(name=self.GetName(), doubleClick=True)
-
+
def Deselect(self):
"""Panel deselected, background changes back to default"""
self.selected = False
self.SetBackgroundColour(self.deselectColor)
self.Refresh()
-
+
def Select(self):
"""Select panel, no event emitted"""
self.selected = True
self.SetBackgroundColour(self.selectColor)
self.Refresh()
-
+
+
class GListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.CheckListCtrlMixin):
"""Generic ListCtrl with popup menu to select/deselect all
items"""
def __init__(self, parent):
self.parent = parent
-
- wx.ListCtrl.__init__(self, parent, id = wx.ID_ANY,
- style = wx.LC_REPORT)
+
+ wx.ListCtrl.__init__(self, parent, id=wx.ID_ANY,
+ style=wx.LC_REPORT)
listmix.CheckListCtrlMixin.__init__(self)
-
+
# setup mixins
listmix.ListCtrlAutoWidthMixin.__init__(self)
-
+
self.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnPopupMenu) #wxMSW
self.Bind(wx.EVT_RIGHT_UP, self.OnPopupMenu) #wxGTK
@@ -841,57 +860,57 @@
"""Show popup menu"""
if self.GetItemCount() < 1:
return
-
+
if not hasattr(self, "popupDataID1"):
self.popupDataID1 = wx.NewId()
self.popupDataID2 = wx.NewId()
-
- self.Bind(wx.EVT_MENU, self.OnSelectAll, id = self.popupDataID1)
- self.Bind(wx.EVT_MENU, self.OnSelectNone, id = self.popupDataID2)
-
+
+ self.Bind(wx.EVT_MENU, self.OnSelectAll, id=self.popupDataID1)
+ self.Bind(wx.EVT_MENU, self.OnSelectNone, id=self.popupDataID2)
+
# generate popup-menu
menu = wx.Menu()
menu.Append(self.popupDataID1, _("Select all"))
menu.Append(self.popupDataID2, _("Deselect all"))
-
+
self.PopupMenu(menu)
menu.Destroy()
def OnSelectAll(self, event):
"""Select all items"""
item = -1
-
+
while True:
item = self.GetNextItem(item)
if item == -1:
break
self.CheckItem(item, True)
-
+
event.Skip()
-
+
def OnSelectNone(self, event):
"""Deselect items"""
item = -1
-
+
while True:
item = self.GetNextItem(item, wx.LIST_STATE_SELECTED)
if item == -1:
break
self.CheckItem(item, False)
-
+
event.Skip()
class SearchModuleWidget(wx.Panel):
"""Search module widget (used e.g. in SearchModuleWindow)
-
+
Signals:
moduleSelected - attribute 'name' is module name
showSearchResult - attribute 'result' is a node (representing module)
showNotification - attribute 'message'
"""
def __init__(self, parent, model,
- showChoice = True, showTip = False, **kwargs):
+ showChoice=True, showTip=False, **kwargs):
self._showTip = showTip
self._showChoice = showChoice
self._model = model
@@ -899,12 +918,12 @@
self._resultIndex = -1
self._searchKeys = ['description', 'keywords', 'command']
self._oldValue = ''
-
+
self.moduleSelected = Signal('SearchModuleWidget.moduleSelected')
self.showSearchResult = Signal('SearchModuleWidget.showSearchResult')
self.showNotification = Signal('SearchModuleWidget.showNotification')
- wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY, **kwargs)
+ wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY, **kwargs)
# self._box = wx.StaticBox(parent = self, id = wx.ID_ANY,
# label = " %s " % _("Find module - (press Enter for next match)"))
@@ -926,7 +945,7 @@
size = (-1, 35))
if self._showChoice:
- self._searchChoice = wx.Choice(parent = self, id = wx.ID_ANY)
+ self._searchChoice = wx.Choice(parent=self, id=wx.ID_ANY)
self._searchChoice.SetItems(self._searchModule(keys=['command'], value=''))
self._searchChoice.Bind(wx.EVT_CHOICE, self.OnSelectModule)
@@ -951,7 +970,7 @@
boxSizer.Add(item=self._searchTip,
flag=wx.ALIGN_CENTER_VERTICAL | wx.EXPAND)
- sizer.Add(item = boxSizer, proportion = 1)
+ sizer.Add(item=boxSizer, proportion=1)
self.SetSizer(sizer)
sizer.Fit(self)
@@ -1004,20 +1023,20 @@
nodes = set()
for key in keys:
nodes.update(self._model.SearchNodes(key=key, value=value))
-
+
nodes = list(nodes)
nodes.sort(key=lambda node: self._model.GetIndexOfNode(node))
self._results = nodes
self._resultIndex = -1
commands = [node.data['command'] for node in nodes if node.data['command']]
commands.sort() # return sorted list of commands (TODO: sort in better way)
-
+
return commands
-
+
def OnSelectModule(self, event):
"""Module selected from choice, update command prompt"""
cmd = self._searchChoice.GetStringSelection()
- self.moduleSelected.emit(name = cmd)
+ self.moduleSelected.emit(name=cmd)
if self._showTip:
for module in self._results:
@@ -1031,6 +1050,7 @@
if self._showTip:
self._searchTip.SetLabel('')
+
class ManageSettingsWidget(wx.Panel):
"""Widget which allows loading and saving settings into file."""
def __init__(self, parent, settingsFile):
@@ -1052,17 +1072,17 @@
self.settingsSaving = Signal('ManageSettingsWidget.settingsSaving')
self.settingsLoaded = Signal('ManageSettingsWidget.settingsLoaded')
- wx.Panel.__init__(self, parent = parent, id = wx.ID_ANY)
+ wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
- self.settingsBox = wx.StaticBox(parent = self, id = wx.ID_ANY,
- label = " %s " % _("Settings"))
-
- self.settingsChoice = wx.Choice(parent = self, id = wx.ID_ANY)
+ self.settingsBox = wx.StaticBox(parent=self, id=wx.ID_ANY,
+ label=" %s " % _("Settings"))
+
+ self.settingsChoice = wx.Choice(parent=self, id=wx.ID_ANY)
self.settingsChoice.Bind(wx.EVT_CHOICE, self.OnSettingsChanged)
- self.btnSettingsSave = wx.Button(parent = self, id = wx.ID_SAVE)
+ self.btnSettingsSave = wx.Button(parent=self, id=wx.ID_SAVE)
self.btnSettingsSave.Bind(wx.EVT_BUTTON, self.OnSettingsSave)
self.btnSettingsSave.SetToolTipString(_("Save current settings"))
- self.btnSettingsDel = wx.Button(parent = self, id = wx.ID_REMOVE)
+ self.btnSettingsDel = wx.Button(parent=self, id=wx.ID_REMOVE)
self.btnSettingsDel.Bind(wx.EVT_BUTTON, self.OnSettingsDelete)
self.btnSettingsSave.SetToolTipString(_("Delete currently selected settings"))
@@ -1083,20 +1103,16 @@
def _layout(self):
self.settingsSizer = wx.StaticBoxSizer(self.settingsBox, wx.HORIZONTAL)
- self.settingsSizer.Add(item = wx.StaticText(parent = self,
- id = wx.ID_ANY,
- label = _("Load settings:")),
- flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
- border = 5)
- self.settingsSizer.Add(item = self.settingsChoice,
- proportion = 1,
- flag = wx.EXPAND)
- self.settingsSizer.Add(item = self.btnSettingsSave,
- flag = wx.LEFT | wx.RIGHT,
- border = 5)
- self.settingsSizer.Add(item = self.btnSettingsDel,
- flag = wx.RIGHT,
- border = 5)
+ self.settingsSizer.Add(item=wx.StaticText(parent=self, id=wx.ID_ANY,
+ label=_("Load settings:")),
+ flag=wx.ALIGN_CENTER_VERTICAL | wx.RIGHT,
+ border=5)
+ self.settingsSizer.Add(item=self.settingsChoice,
+ proportion=1, flag=wx.EXPAND)
+ self.settingsSizer.Add(item=self.btnSettingsSave,
+ flag=wx.LEFT | wx.RIGHT, border=5)
+ self.settingsSizer.Add(item=self.btnSettingsDel,
+ flag=wx.RIGHT,border=5)
def OnSettingsChanged(self, event):
"""Load named settings"""
@@ -1112,28 +1128,29 @@
def GetSettings(self):
"""Load named settings"""
return self._settings.copy()
-
+
def OnSettingsSave(self, event):
"""Save settings"""
- dlg = wx.TextEntryDialog(parent = self,
- message = _("Name:"),
- caption = _("Save settings"))
+ dlg = wx.TextEntryDialog(parent=self,
+ message=_("Name:"),
+ caption=_("Save settings"))
if dlg.ShowModal() == wx.ID_OK:
name = dlg.GetValue()
if not name:
- GMessage(parent = self,
- message = _("Name not given, settings is not saved."))
+ GMessage(parent=self,
+ message=_("Name not given, settings is not saved."))
else:
self.settingsSaving.emit(name=name)
-
+
dlg.Destroy()
-
+
def SaveSettings(self, name):
# check if settings item already exists
if name in self._settings:
- dlgOwt = wx.MessageDialog(self, message = _("Settings <%s> already exists. "
- "Do you want to overwrite the settings?") % name,
- caption = _("Save settings"), style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
+ dlgOwt = wx.MessageDialog(self, message=_("Settings <%s> already exists. "
+ "Do you want to overwrite the settings?") % name,
+ caption=_("Save settings"),
+ style=wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if dlgOwt.ShowModal() != wx.ID_YES:
dlgOwt.Destroy()
return
@@ -1145,7 +1162,7 @@
self.settingsChoice.SetStringSelection(name)
self.data_to_save = []
-
+
def _saveSettings(self):
"""Save settings and reload if successful"""
if self._writeSettings() == 0:
@@ -1182,11 +1199,11 @@
GMessage(parent = self,
message = _("No settings is defined. Operation canceled."))
return
-
+
self._settings.pop(name)
if self._writeSettings() == 0:
self._settings = self._loadSettings()
-
+
def _writeSettings(self):
"""Save settings into the file
@@ -1217,14 +1234,14 @@
message = _("Unable to save settings"))
return -1
fd.close()
-
+
return 0
def _loadSettings(self):
"""Load settings from the file
The file is defined by self.SettingsFile.
-
+
:return: parsed dict
:return: empty dict on error
"""
@@ -1260,12 +1277,12 @@
"""Load settings from the file in format version 2.0
The file is defined by self.SettingsFile.
-
+
:return: parsed dict
:return: empty dict on error
"""
data = dict()
-
+
for line in fd_lines[1:]:
try:
lineData = []
@@ -1285,7 +1302,7 @@
while True:
if line[idx - (i_esc_chars + 1)] == self.esc_chars[self.e_char_i]:
i_esc_chars += 1
- else:
+ else:
break
if i_esc_chars%2 != 0:
i_last = idx + 1
@@ -1311,12 +1328,12 @@
"""Load settings from the file in format version 1.0 (backward compatibility)
The file is defined by self.SettingsFile.
-
+
:return: parsed dict
:return: empty dict on error
"""
data = dict()
-
+
for line in fd_lines:
try:
lineData = line.rstrip('\n').split(';')
@@ -1327,17 +1344,17 @@
data[lineData[0]] = (lineData[1], lineData[2], lineData[3], '')
except ValueError:
pass
-
+
return data
class PictureComboBox(wx.combo.OwnerDrawnComboBox):
"""Abstract class of ComboBox with pictures.
-
+
Derived class has to specify has to specify _getPath method.
"""
def OnDrawItem(self, dc, rect, item, flags):
"""Overridden from OwnerDrawnComboBox.
-
+
Called to draw each item in the list.
"""
if item == wx.NOT_FOUND:
@@ -1367,8 +1384,8 @@
def GetPictureBitmap(self, name):
"""Returns bitmap for given picture name.
-
- :param str colorTable: name of color table
+
+ :param str colorTable: name of color table
"""
if not hasattr(self, 'bitmaps'):
self.bitmaps = {}
Modified: grass/trunk/gui/wxpython/lmgr/giface.py
===================================================================
--- grass/trunk/gui/wxpython/lmgr/giface.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/lmgr/giface.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -24,8 +24,10 @@
class Layer(object):
"""@implements core::giface::Layer
- .. note:: Currently implemented without specifying the interface.
- It only provides all attributes of existing layer as used in lmgr.
+ .. note::
+
+ Currently implemented without specifying the interface.
+ It only provides all attributes of existing layer as used in lmgr.
"""
def __init__(self, pydata):
self._pydata = pydata
@@ -150,15 +152,18 @@
cmdlist = ['g.manual', 'entry=%s' % entry]
if online:
cmdlist.append('-o')
- self.RunCmd(cmdlist, compReg = False, notification=Notification.NO_NOTIFICATION)
+ self.RunCmd(cmdlist, compReg=False,
+ notification=Notification.NO_NOTIFICATION)
- def WriteLog(self, text, wrap = None,
+ def WriteLog(self, text, wrap=None,
notification=Notification.HIGHLIGHT):
- self.lmgr._gconsole.WriteLog(text=text, wrap=wrap,
+ self.lmgr._gconsole.WriteLog(text=text, wrap=wrap,
notification=notification)
- def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE):
- self.lmgr._gconsole.WriteCmdLog(text=text, pid=pid, notification=notification)
+ def WriteCmdLog(self, text, pid=None,
+ notification=Notification.MAKE_VISIBLE):
+ self.lmgr._gconsole.WriteCmdLog(text=text, pid=pid,
+ notification=notification)
def WriteWarning(self, text):
self.lmgr._gconsole.WriteWarning(text=text)
@@ -190,6 +195,7 @@
def UpdateCmdHistory(self, cmd):
self.lmgr.goutput.GetPrompt().UpdateCmdHistory(cmd)
+
class LayerManagerGrassInterfaceForMapDisplay(object):
"""Provides reference only to the given layer list (according to tree),
not to the current.
Modified: grass/trunk/gui/wxpython/mapdisp/frame.py
===================================================================
--- grass/trunk/gui/wxpython/mapdisp/frame.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/mapdisp/frame.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -30,7 +30,6 @@
import wx
import wx.aui
-from core import globalvar
from core.render import Map
from vdigit.toolbars import VDigitToolbar
from mapdisp.toolbars import MapToolbar, NvizIcons
@@ -1307,7 +1306,7 @@
def IsStandalone(self):
"""Check if Map display is standalone
- .. deprecated::
+ .. deprecated:: 7.0
"""
# TODO: once it is removed from 2 places in vdigit it can be deleted
# here and also in base class and other classes in the tree (hopefully)
@@ -1317,22 +1316,22 @@
" Signals or giface")
if self._layerManager:
return False
-
+
return True
-
+
def GetLayerManager(self):
"""Get reference to Layer Manager
:return: window reference
:return: None (if standalone)
- .. deprecated::
+ .. deprecated:: 7.0
"""
Debug.msg(1, "MapFrame.GetLayerManager(): Method GetLayerManager is"
"depreciated, use some general approach instead such as"
" Signals or giface")
return self._layerManager
-
+
def GetMapToolbar(self):
"""Returns toolbar with zooming tools"""
return self.toolbars['map']
Modified: grass/trunk/gui/wxpython/mapwin/base.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/base.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/mapwin/base.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -52,6 +52,7 @@
self._alignExtent = UserSettings.Get(group='display',
key='alignExtent',
subkey='enabled')
+
@property
def resolution(self):
return self._resolution
@@ -95,10 +96,10 @@
class MapWindowBase(object):
"""Abstract map display window class
-
+
Superclass for BufferedWindow class (2D display mode), and GLWindow
(3D display mode).
-
+
Subclasses have to define
- _bindMouseEvents method which binds MouseEvent handlers
- Pixel2Cell
@@ -127,8 +128,8 @@
'box' : "point"
}
# last east, north coordinates, changes on mouse motion
- self.lastEN = None
-
+ self.lastEN = None
+
# stores overridden cursor
self._overriddenCursor = None
@@ -177,10 +178,10 @@
"""
for ev, handlers in self.handlersContainer.iteritems():
self.Bind(ev, self.EventTypeHandler(handlers))
-
+
def EventTypeHandler(self, evHandlers):
- return lambda event:self.HandlersCaller(event, evHandlers)
-
+ return lambda event : self.HandlersCaller(event, evHandlers)
+
def HandlersCaller(self, event, handlers):
"""Hepler function which calls all handlers registered for
event
@@ -190,53 +191,54 @@
handler(event)
except:
handlers.remove(handler)
- GError(parent = self,
+ GError(parent=self,
message=_("Error occured during calling of handler: %s \n"
"Handler was unregistered.") % handler.__name__)
-
+
event.Skip()
- def RegisterMouseEventHandler(self, event, handler, cursor = None):
+ def RegisterMouseEventHandler(self, event, handler, cursor=None):
"""Binds event handler
- @depreciated This method is depreciated. Use Signals or drawing API instead.
- Signals do not cover all events but new Signals can be added when needed
- consider also adding generic signal. However, more interesing and useful
- is higher level API to create objects, graphics etc.
+ @depreciated This method is depreciated. Use Signals or drawing API
+ instead. Signals do not cover all events but new Signals can be added
+ when needed consider also adding generic signal. However, more
+ interesing and useful is higher level API to create objects, graphics etc.
Call event.Skip() in handler to allow default processing in MapWindow.
If any error occures inside of handler, the handler is removed.
- Before handler is unregistered it is called with
+ Before handler is unregistered it is called with
string value "unregistered" of event parameter.
- @code
- # your class methods
- def OnButton(self, event):
- # current map display's map window
- # expects LayerManager to be the parent
- self.mapwin = self.parent.GetLayerTree().GetMapDisplay().GetWindow()
- if self.mapwin.RegisterEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction,
- 'cross'):
- self.parent.GetLayerTree().GetMapDisplay().Raise()
- else:
- # handle that you cannot get coordinates
-
- def OnMouseAction(self, event):
- # get real world coordinates of mouse click
- coor = self.mapwin.Pixel2Cell(event.GetPositionTuple()[:])
- self.text.SetLabel('Coor: ' + str(coor))
- self.mapwin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction)
- event.Skip()
- @endcode
+ ::
- Emits mouseHandlerRegistered signal before handler is registered.
+ # your class methods
+ def OnButton(self, event):
+ # current map display's map window
+ # expects LayerManager to be the parent
+ self.mapwin = self.parent.GetLayerTree().GetMapDisplay().GetWindow()
+ if self.mapwin.RegisterEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction,
+ 'cross'):
+ self.parent.GetLayerTree().GetMapDisplay().Raise()
+ else:
+ # handle that you cannot get coordinates
+ def OnMouseAction(self, event):
+ # get real world coordinates of mouse click
+ coor = self.mapwin.Pixel2Cell(event.GetPositionTuple()[:])
+ self.text.SetLabel('Coor: ' + str(coor))
+ self.mapwin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction)
+ event.Skip()
+
+
+ Emits mouseHandlerRegistered signal before handler is registered.
+
:param event: one of mouse events
:param handler: function to handle event
:param cursor: cursor which temporary overrides current cursor
-
+
:return: True if successful
:return: False if event cannot be bind
"""
Modified: grass/trunk/gui/wxpython/mapwin/buffered.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/buffered.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/mapwin/buffered.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -49,11 +49,12 @@
except ImportError:
haveCtypes = False
+
class BufferedMapWindow(MapWindowBase, wx.Window):
"""A Buffered window class (2D view mode)
Superclass for VDigitWindow (vector digitizer).
-
+
When the drawing needs to change, you app needs to call the
UpdateMap() method. Since the drawing is stored in a bitmap, you
can also save the drawing to file by calling the
@@ -80,7 +81,7 @@
self.resize = False # indicates whether or not a resize event has taken place
self.dragimg = None # initialize variable for map panning
self.alwaysRender = False # if it always sets render to True in self.UpdateMap()
-
+
# variables for drawing on DC
self.pen = None # pen for drawing zoom boxes, etc.
self.polypen = None # pen for drawing polylines (measurements, profiles, etc)
@@ -92,7 +93,7 @@
self.plineid = None
# following class members deals with merging more updateMap request
- # into one UpdateMap process
+ # into one UpdateMap process
# thread where timer for measuring delay limit
self.renderTimingThr = gThread()
@@ -103,7 +104,7 @@
# defines time limit for waiting for another update request
self.updDelay = 0
# holds information about level of rendering during the delay limit
- self.render = self.renderVector = False
+ self.render = self.renderVector = False
# Emitted when zoom of a window is changed
self.zoomChanged = Signal('BufferedWindow.zoomChanged')
@@ -141,9 +142,9 @@
self.Bind(wx.EVT_IDLE, self.OnIdle)
self._bindMouseEvents()
-
+
self.processMouse = True
-
+
# render output objects
self.mapfile = None # image file to be rendered
self.img = None # wx.Image object (self.mapfile)
@@ -151,43 +152,43 @@
self.overlays = overlays
self._overlayNames = {0: _("legend"), 1: _("scale bar"), 2: _("north arrow")}
# images and their PseudoDC ID's for painting and dragging
- self.imagedict = {}
+ self.imagedict = {}
self.select = {} # selecting/unselecting decorations for dragging
self.textdict = {} # text, font, and color indexed by id
-
+
# zoom objects
self.zoomhistory = [] # list of past zoom extents
self.currzoom = 0 # current set of extents in zoom history being used
self.zoomtype = 1 # 1 zoom in, 0 no zoom, -1 zoom out
self.hitradius = 10 # distance for selecting map decorations
self.dialogOffset = 5 # offset for dialog (e.g. DisplayAttributesDialog)
-
+
# OnSize called to make sure the buffer is initialized.
# This might result in OnSize getting called twice on some
# platforms at initialization, but little harm done.
### self.OnSize(None)
-
+
self._definePseudoDC()
# redraw all pdc's, pdcTmp layer is redrawn always (speed issue)
self.redrawAll = True
-
+
# will store an off screen empty bitmap for saving to file
self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
-
+
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda x:None)
# rerender when Map reports change
self.Map.layerChanged.connect(self.OnUpdateMap)
-
+
# vars for handling mouse clicks
self.dragid = -1
self.lastpos = (0, 0)
-
+
# list for registration of graphics to draw
self.graphicsSetList = []
def OnUpdateMap(self):
- # before lambda func was used, however it was problem
+ # before lambda func was used, however it was problem
# to disconnect it from signal
self.UpdateMap()
@@ -210,7 +211,7 @@
self.pdcDec = wx.PseudoDC()
# pseudoDC for temporal objects (select box, measurement tool, etc.)
self.pdcTmp = wx.PseudoDC()
-
+
def _bindMouseEvents(self):
self.Bind(wx.EVT_MOUSE_EVENTS, self.MouseActions)
self.Bind(wx.EVT_MOTION, self.OnMotion)
@@ -259,7 +260,7 @@
drawid = None
else:
drawid = wx.NewId()
-
+
# TODO: find better solution
if not pen:
if pdctype == 'polyline':
@@ -270,23 +271,23 @@
if img and pdctype == 'image':
# self.imagedict[img]['coords'] = coords
self.select[self.imagedict[img]['id']] = False # ?
-
+
pdc.BeginDrawing()
-
+
if drawid != 99:
bg = wx.TRANSPARENT_BRUSH
else:
bg = wx.Brush(self.GetBackgroundColour())
-
+
pdc.SetBackground(bg)
-
+
Debug.msg (5, "BufferedWindow.Draw(): id=%s, pdctype = %s, coord=%s" % \
(drawid, pdctype, coords))
-
+
# set PseudoDC id
if drawid is not None:
pdc.SetId(drawid)
-
+
if pdctype == 'clear': # erase the display
bg = wx.WHITE_BRUSH
# bg = wx.Brush(self.GetBackgroundColour())
@@ -294,16 +295,16 @@
pdc.RemoveAll()
pdc.Clear()
pdc.EndDrawing()
-
+
self.Refresh()
return
-
+
if pdctype == 'image': # draw selected image
bitmap = wx.BitmapFromImage(img)
w,h = bitmap.GetSize()
pdc.DrawBitmap(bitmap, coords[0], coords[1], True) # draw the composite map
pdc.SetIdBounds(drawid, wx.Rect(coords[0],coords[1], w, h))
-
+
elif pdctype == 'box': # draw a box on top of the map
if pen:
pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
@@ -317,7 +318,7 @@
rect = wx.Rect(x1, y1, rwidth, rheight)
pdc.DrawRectangleRect(rect)
pdc.SetIdBounds(drawid, rect)
-
+
elif pdctype == 'line': # draw a line on top of the map
if pen:
pdc.SetBrush(wx.Brush(wx.CYAN, wx.TRANSPARENT))
@@ -392,7 +393,7 @@
coords[0] + 5,
coords[1] + 5)
pdc.SetIdBounds(drawid, wx.Rect(coordsBound))
-
+
elif pdctype == 'text': # draw text on top of map
if not img['active']:
return # only draw active text
@@ -412,19 +413,19 @@
else:
pdc.DrawRotatedText(img['text'], coords[0], coords[1], rotation)
pdc.SetIdBounds(drawid, bbox)
-
+
pdc.EndDrawing()
-
+
self.Refresh()
-
+
return drawid
-
+
def TextBounds(self, textinfo, relcoords = False):
"""Return text boundary data
-
+
:param textinfo: text metadata (text, font, color, rotation)
:param coords: reference point
-
+
:return: coords of nonrotated text bbox (TL corner)
:return: bbox of rotated text bbox (wx.Rect)
:return: relCoords are text coord inside bbox
@@ -433,26 +434,26 @@
rotation = float(textinfo['rotation'])
else:
rotation = 0.0
-
+
coords = textinfo['coords']
bbox = wx.Rect(coords[0], coords[1], 0, 0)
relCoords = (0, 0)
Debug.msg (4, "BufferedWindow.TextBounds(): text=%s, rotation=%f" % \
(textinfo['text'], rotation))
-
+
self.Update()
-
+
self.SetFont(textinfo['font'])
-
+
w, h = self.GetTextExtent(textinfo['text'])
-
+
if rotation == 0:
bbox[2], bbox[3] = w, h
if relcoords:
return coords, bbox, relCoords
else:
return coords, bbox
-
+
boxh = math.fabs(math.sin(math.radians(rotation)) * w) + h
boxw = math.fabs(math.cos(math.radians(rotation)) * w) + h
if rotation > 0 and rotation < 90:
@@ -475,31 +476,31 @@
def OnPaint(self, event):
"""Draw PseudoDC's to buffered paint DC
-
+
If self.redrawAll is False on self.pdcTmp content is re-drawn
"""
Debug.msg(4, "BufferedWindow.OnPaint(): redrawAll=%s" % self.redrawAll)
dc = wx.BufferedPaintDC(self, self._buffer)
dc.Clear()
-
+
# use PrepareDC to set position correctly
# probably does nothing, removed from wxPython 2.9
# self.PrepareDC(dc)
-
+
# create a clipping rect from our position and size
# and update region
rgn = self.GetUpdateRegion().GetBox()
dc.SetClippingRect(rgn)
-
+
switchDraw = False
if self.redrawAll is None:
self.redrawAll = True
switchDraw = True
-
+
if self.redrawAll: # redraw pdc and pdcVector
# draw to the dc using the calculated clipping rect
self.pdc.DrawToDCClipped(dc, rgn)
-
+
# draw vector map layer
if hasattr(self, "digit"):
# decorate with GDDC (transparency)
@@ -509,13 +510,13 @@
except NotImplementedError as e:
print >> sys.stderr, e
self.pdcVector.DrawToDCClipped(dc, rgn)
-
+
self.bufferLast = None
else: # do not redraw pdc and pdcVector
if self.bufferLast is None:
# draw to the dc
self.pdc.DrawToDC(dc)
-
+
if hasattr(self, "digit"):
# decorate with GDDC (transparency)
try:
@@ -524,14 +525,14 @@
except NotImplementedError as e:
print >> sys.stderr, e
self.pdcVector.DrawToDC(dc)
-
+
# store buffered image
# self.bufferLast = wx.BitmapFromImage(self.buffer.ConvertToImage())
self.bufferLast = dc.GetAsBitmap(wx.Rect(0, 0, self.Map.width, self.Map.height))
-
+
self.pdc.DrawBitmap(self.bufferLast, 0, 0, False)
self.pdc.DrawToDC(dc)
-
+
# draw decorations (e.g. region box)
try:
gcdc = wx.GCDC(dc)
@@ -539,14 +540,14 @@
except NotImplementedError as e:
print >> sys.stderr, e
self.pdcDec.DrawToDC(dc)
-
+
# draw temporary object on the foreground
### self.pdcTmp.DrawToDCClipped(dc, rgn)
self.pdcTmp.DrawToDC(dc)
-
+
if switchDraw:
self.redrawAll = False
-
+
def OnSize(self, event):
"""Scale map image so that it is the same size as the Window
"""
@@ -557,12 +558,12 @@
"""Only re-render a composite map image from GRASS during
idle time instead of multiple times during resizing.
"""
-
+
# use OnInternalIdle() instead ?
if self.resize and self.resize + 0.2 < time.clock():
Debug.msg(3, "BufferedWindow.OnSize():")
-
+
# set size of the input image
self.Map.ChangeMapSize(self.GetClientSize())
@@ -571,10 +572,10 @@
# a file, or whatever.
self._buffer.Destroy()
self._buffer = wx.EmptyBitmap(max(1, self.Map.width), max(1, self.Map.height))
-
+
# get the image to be rendered
self.img = self.GetImage()
-
+
# update map display
updatemap = True
if self.img and self.Map.width + self.Map.height > 0: # scale image after resize
@@ -588,13 +589,13 @@
self.resize = False
elif self.resize:
event.RequestMore()
-
+
event.Skip()
def SaveToFile(self, FileName, FileType, width, height):
"""This draws the pseudo DC to a buffer that can be saved to
a file.
-
+
:param filename: file name
:param FileType: type of bitmap
:param width: image width
@@ -603,18 +604,18 @@
busy = wx.BusyInfo(message = _("Please wait, exporting image..."),
parent = self)
wx.Yield()
-
+
self.Map.ChangeMapSize((width, height))
ibuffer = wx.EmptyBitmap(max(1, width), max(1, height))
self.Map.Render(force = True, windres = self._properties.resolution)
img = self.GetImage()
self.pdc.RemoveAll()
self.Draw(self.pdc, img, drawid = 99)
-
+
# compute size ratio to move overlay accordingly
cSize = self.GetClientSizeTuple()
ratio = float(width) / cSize[0], float(height) / cSize[1]
-
+
# redraw legend, scalebar
for img in self.GetOverlay():
# draw any active and defined overlays
@@ -624,7 +625,7 @@
int(ratio[1] * self.overlays[id].coords[1])
self.Draw(self.pdc, img = img, drawid = id,
pdctype = self.overlays[id].pdcType, coords = coords)
-
+
# redraw text labels
for id in self.textdict.keys():
textinfo = self.textdict[id]
@@ -635,7 +636,7 @@
pdctype = 'text')
# set back old coordinates
textinfo['coords'] = oldCoords
-
+
dc = wx.BufferedDC(None, ibuffer)
dc.Clear()
# probably does nothing, removed from wxPython 2.9
@@ -644,17 +645,17 @@
if self.pdcVector:
self.pdcVector.DrawToDC(dc)
ibuffer.SaveFile(FileName, FileType)
-
+
busy.Destroy()
-
+
self.UpdateMap(render = True)
self.Refresh()
-
+
def GetOverlay(self):
"""Converts rendered overlay files to wx.Image
-
+
Updates self.imagedict
-
+
:return: list of images
"""
imgs = []
@@ -666,18 +667,18 @@
for key in self.imagedict.keys():
if self.imagedict[key]['id'] == overlay.id:
del self.imagedict[key]
-
+
self.imagedict[img] = { 'id' : overlay.id,
'layer' : overlay }
imgs.append(img)
return imgs
-
+
def GetImage(self):
"""Converts redered map files to wx.Image
-
+
Updates self.imagedict (id=99)
-
+
:return: wx.Image instance (map composition)
"""
imgId = 99
@@ -686,25 +687,25 @@
img = wx.Image(self.Map.mapfile, wx.BITMAP_TYPE_ANY)
else:
img = None
-
+
for key in self.imagedict.keys():
if self.imagedict[key]['id'] == imgId:
del self.imagedict[key]
self.imagedict[img] = { 'id': imgId }
-
+
return img
def SetAlwaysRenderEnabled(self, alwaysRender = True):
self.alwaysRender = alwaysRender
-
+
def IsAlwaysRenderEnabled(self):
return self.alwaysRender
def UpdateMap(self, render=True, renderVector=True, delay=0.0):
"""Updates the canvas anytime there is a change to the
underlaying images or to the geometry of the canvas.
-
+
This method should not be called directly.
.. todo::
@@ -717,8 +718,8 @@
:param render: re-render map composition
:param renderVector: re-render vector map layer enabled for editing (used for digitizer)
- :param delay: defines time threshold in seconds for postponing
- rendering to merge more update requests.
+ :param delay: defines time threshold in seconds for postponing
+ rendering to merge more update requests.
If another request comes within the limit, rendering is delayed
again. Next delay limit is chosen according to the smallest
@@ -739,7 +740,7 @@
if self.timerRunId is None or delay < self.updDelay:
self.updDelay = delay
-
+
if render:
self.render = render
if renderVector:
@@ -752,14 +753,14 @@
self._runUpdateMap()
else:
self.timerRunId = self.renderTimingThr.GetId()
- self.renderTimingThr.Run(callable=self._timingFunction,
- ondone=self._onUpdateMap,
+ self.renderTimingThr.Run(callable=self._timingFunction,
+ ondone=self._onUpdateMap,
pid=self.timerRunId)
def _timingFunction(self, pid):
"""Timer measuring elapsed time, since last update request.
- It terminates, when delay limit is exceeded.
+ It terminates, when delay limit is exceeded.
:param pid: id which defines whether it is newest timer, or
there is another one (representing newer Update map
@@ -787,12 +788,12 @@
"""
start = time.clock()
self.resize = False
-
+
# was if self.Map.cmdfile and ...
if self.IsAlwaysRenderEnabled() and self.img is None:
render = True
-
+
#
# render background image if needed
#
@@ -811,18 +812,18 @@
windres = True
else:
windres = False
-
+
self.mapfile = self.Map.Render(force = True,
windres = windres)
else:
self.mapfile = self.Map.Render(force = False)
-
+
except GException as e:
GError(message = e.value)
self.mapfile = None
-
+
self.img = self.GetImage() # id=99
-
+
#
# clear pseudoDcs
#
@@ -831,7 +832,7 @@
self.pdcTmp):
pdc.Clear()
pdc.RemoveAll()
-
+
#
# draw background map image to PseudoDC
#
@@ -842,9 +843,9 @@
id = self.imagedict[self.img]['id']
except:
return False
-
+
self.Draw(self.pdc, self.img, drawid = id)
-
+
#
# render vector map layer
#
@@ -859,23 +860,23 @@
id = self.imagedict[img]['id']
self.Draw(self.pdc, img = img, drawid = id,
pdctype = self.overlays[id].pdcType, coords = self.overlays[id].coords)
-
+
for id in self.textdict.keys():
self.Draw(self.pdc, img = self.textdict[id], drawid = id,
pdctype = 'text', coords = [10, 10, 10, 10])
-
+
# optionally draw computational extent box
self.DrawCompRegionExtent()
-
+
#
# redraw pdcTmp if needed
#
-
+
# draw registered graphics
if len(self.graphicsSetList) > 0:
penOrig = self.pen
polypenOrig = self.polypen
-
+
for item in self.graphicsSetList:
try:
item.Draw(self.pdcTmp)
@@ -883,24 +884,24 @@
GError(parent = self,
message = _('Unable to draw registered graphics. '
'The graphics was unregistered.'))
- self.UnregisterGraphicsToDraw(item)
-
- self.pen = penOrig
- self.polypen = polypenOrig
-
+ self.UnregisterGraphicsToDraw(item)
+
+ self.pen = penOrig
+ self.polypen = polypenOrig
+
if len(self.polycoords) > 0:
self.DrawLines(self.pdcTmp)
-
+
stop = time.clock()
-
+
Debug.msg (1, "BufferedWindow.UpdateMap(): render=%s, renderVector=%s -> time=%g" % \
(render, renderVector, (stop-start)))
-
+
return True
def DrawCompRegionExtent(self):
"""Draw computational region extent in the display
-
+
Display region is drawn as a blue box inside the computational region,
computational region inside a display region as a red box).
"""
@@ -929,10 +930,10 @@
"""Erase map canvas
"""
self.Draw(self.pdc, pdctype = 'clear')
-
+
if hasattr(self, "digit"):
self.Draw(self.pdcVector, pdctype = 'clear')
-
+
self.Draw(self.pdcDec, pdctype = 'clear')
self.Draw(self.pdcTmp, pdctype = 'clear')
@@ -940,21 +941,21 @@
def DragMap(self, moveto):
"""Drag the entire map image for panning.
-
+
:param moveto: dx,dy
"""
dc = wx.BufferedDC(wx.ClientDC(self))
dc.SetBackground(wx.Brush("White"))
dc.Clear()
-
+
self.dragimg = wx.DragImage(self._buffer)
self.dragimg.BeginDrag((0, 0), self)
self.dragimg.GetImageRect(moveto)
self.dragimg.Move(moveto)
-
+
self.dragimg.DoDrawImage(dc, moveto)
self.dragimg.EndDrag()
-
+
def DragItem(self, id, coords):
"""Drag an overlay decoration item
"""
@@ -965,7 +966,7 @@
dy = coords[1] - y
self.pdc.SetBackground(wx.Brush(self.GetBackgroundColour()))
r = self.pdc.GetIdBounds(id)
-
+
if type(r) is list:
r = wx.Rect(r[0], r[1], r[2], r[3])
if id > 100: # text dragging
@@ -974,7 +975,7 @@
rleft = (r[0]-r[2],r[1],r[2],r[3])
r = r.Union(rleft)
self.pdc.TranslateId(id, dx, dy)
-
+
r2 = self.pdc.GetIdBounds(id)
if type(r2) is list:
r2 = wx.Rect(r[0], r[1], r[2], r[3])
@@ -986,24 +987,24 @@
r.Inflate(4,4)
self.RefreshRect(r, False)
self.lastpos = (coords[0], coords[1])
-
+
def MouseDraw(self, pdc = None, begin = None, end = None):
"""Mouse box or line from 'begin' to 'end'
-
+
If not given from self.mouse['begin'] to self.mouse['end'].
"""
if not pdc:
return
-
+
if begin is None:
begin = self.mouse['begin']
if end is None:
end = self.mouse['end']
-
+
Debug.msg (5, "BufferedWindow.MouseDraw(): use=%s, box=%s, begin=%f,%f, end=%f,%f" % \
(self.mouse['use'], self.mouse['box'],
begin[0], begin[1], end[0], end[1]))
-
+
if self.mouse['box'] == "box":
boxid = wx.ID_NEW
mousecoords = [begin[0], begin[1],
@@ -1019,7 +1020,7 @@
self.RefreshRect(r, False)
pdc.SetId(boxid)
self.Draw(pdc, drawid = boxid, pdctype = 'box', coords = mousecoords)
-
+
elif self.mouse['box'] == "line":
self.lineid = wx.ID_NEW
mousecoords = [begin[0], begin[1], \
@@ -1040,19 +1041,19 @@
def DrawLines(self, pdc = None, polycoords = None):
"""Draw polyline in PseudoDC
-
+
Set self.pline to wx.NEW_ID + 1
-
+
:param polycoords: list of polyline vertices, geographical
coordinates (if not given, self.polycoords
is used)
"""
if not pdc:
pdc = self.pdcTmp
-
+
if not polycoords:
polycoords = self.polycoords
-
+
if len(polycoords) > 0:
self.plineid = wx.ID_NEW + 1
# convert from EN to XY
@@ -1061,20 +1062,20 @@
coords.append(self.Cell2Pixel(p))
self.Draw(pdc, drawid = self.plineid, pdctype = 'polyline', coords = coords)
-
+
Debug.msg (4, "BufferedWindow.DrawLines(): coords=%s, id=%s" % \
(coords, self.plineid))
-
+
return self.plineid
-
+
return -1
def DrawPolylines(self, pdc, coords, pen, drawid=None):
"""Draw polyline in PseudoDC.
-
+
This is similar to DrawLines but this is used with GraphicsSet,
coordinates should be always in pixels.
-
+
:param pdc: PseudoDC
:param coords: list of coordinates (pixel coordinates)
:param pen: pen to be used
@@ -1118,10 +1119,10 @@
coord = [coords[0] + textOffset[0], coords[1] + textOffset[1], 0, 0]
else:
coord = [coords[0] - textOffset[0], coords[1] + textOffset[1], 0, 0]
-
+
self.Draw(pdc, img = text,
pdctype = 'text', coords = coord, pen = pen)
-
+
return self.lineid
def DrawRectangle(self, pdc, point1, point2, pen, drawid=None):
@@ -1191,52 +1192,52 @@
"""
if not self.processMouse:
return
-
+
# zoom with mouse wheel
if event.GetWheelRotation() != 0:
self.OnMouseWheel(event)
-
+
# left mouse button pressed
elif event.LeftDown():
self.OnLeftDown(event)
-
+
# left mouse button released
elif event.LeftUp():
self.OnLeftUp(event)
-
+
# dragging
elif event.Dragging():
self.OnDragging(event)
-
+
# double click
elif event.ButtonDClick():
self.OnButtonDClick(event)
-
+
# middle mouse button pressed
elif event.MiddleDown():
self.OnMiddleDown(event)
-
+
# middle mouse button relesed
elif event.MiddleUp():
self.OnMiddleUp(event)
-
+
# right mouse button pressed
elif event.RightDown():
self.OnRightDown(event)
-
+
# right mouse button released
elif event.RightUp():
self.OnRightUp(event)
-
+
elif event.Entering():
self.OnMouseEnter(event)
-
+
elif event.Moving():
pixelCoordinates = event.GetPositionTuple()[:]
coordinates = self.Pixel2Cell(pixelCoordinates)
self.mouseMoving.emit(x=coordinates[0], y=coordinates[1])
self.OnMouseMoving(event)
-
+
def OnMouseWheel(self, event):
"""Mouse wheel moved
"""
@@ -1246,12 +1247,12 @@
if zoomBehaviour == 2:
event.Skip()
return
-
+
self.processMouse = False
current = event.GetPositionTuple()[:]
wheel = event.GetWheelRotation()
Debug.msg (5, "BufferedWindow.MouseAction(): wheel=%d" % wheel)
-
+
if wheel > 0:
zoomtype = 1
else:
@@ -1268,17 +1269,17 @@
begin = (current[0]/2, current[1]/2)
end = ((self.Map.width - current[0])/2 + current[0],
(self.Map.height - current[1])/2 + current[1])
-
-
+
+
# zoom
self.Zoom(begin, end, zoomtype)
-
+
# redraw map
self.UpdateMap(delay=0.2)
self.Refresh()
self.processMouse = True
-
+
def OnDragging(self, event):
"""Mouse dragging
"""
@@ -1287,37 +1288,37 @@
previous = self.mouse['begin']
move = (current[0] - previous[0],
current[1] - previous[1])
-
+
if hasattr(self, "digit"):
digitToolbar = self.toolbar
else:
digitToolbar = None
-
+
# dragging or drawing box with left button
if self.mouse['use'] == 'pan' or \
event.MiddleIsDown():
self.DragMap(move)
-
+
# dragging decoration overlay item
- elif (self.mouse['use'] == 'pointer' and
- not digitToolbar and
+ elif (self.mouse['use'] == 'pointer' and
+ not digitToolbar and
self.dragid != None):
coords = event.GetPositionTuple()
self.DragItem(self.dragid, coords)
-
+
# dragging anything else - rubber band box or line
else:
- if (self.mouse['use'] == 'pointer' and
+ if (self.mouse['use'] == 'pointer' and
not digitToolbar):
return
-
+
self.mouse['end'] = event.GetPositionTuple()[:]
- if (event.LeftIsDown() and
- not (digitToolbar and
- digitToolbar.GetAction() in ("moveLine",) and
+ if (event.LeftIsDown() and
+ not (digitToolbar and
+ digitToolbar.GetAction() in ("moveLine",) and
self.digit.GetDisplay().GetSelected() > 0)):
self.MouseDraw(pdc = self.pdcTmp)
-
+
def OnLeftDown(self, event):
"""Left mouse button pressed
"""
@@ -1333,7 +1334,7 @@
self.OnLeftDownUndo(event)
else:
self._onLeftDown(event)
-
+
elif self.mouse['use'] == 'pointer':
# get decoration or text id
idlist = []
@@ -1349,9 +1350,9 @@
pass
coords = self.Pixel2Cell(self.mouse['begin'])
self.mouseLeftDown.emit(x=coords[0], y=coords[1])
-
+
event.Skip()
-
+
def OnLeftUp(self, event):
"""Left mouse button released
@@ -1359,15 +1360,15 @@
"""
Debug.msg (5, "BufferedWindow.OnLeftUp(): use=%s" % \
self.mouse["use"])
-
+
self.mouse['end'] = event.GetPositionTuple()[:]
coordinates = self.Pixel2Cell(self.mouse['end'])
-
+
if self.mouse['use'] in ["zoom", "pan"]:
# set region in zoom or pan
begin = self.mouse['begin']
end = self.mouse['end']
-
+
if self.mouse['use'] == 'zoom':
# set region for click (zero-width box)
if begin[0] - end[0] == 0 or \
@@ -1384,11 +1385,11 @@
elif self.mouse["use"] == "pointer" and \
hasattr(self, "digit"):
self._onLeftUp(event)
-
- elif (self.mouse['use'] == 'pointer' and
+
+ elif (self.mouse['use'] == 'pointer' and
self.dragid >= 0):
# end drag of overlay decoration
-
+
if self.dragid < 99 and self.dragid in self.overlays:
self.overlays[self.dragid].coords = self.pdc.GetIdBounds(self.dragid)
elif self.dragid > 100 and self.dragid in self.textdict:
@@ -1398,10 +1399,10 @@
self.dragid = None
self.mouseLeftUpPointer.emit(x=coordinates[0], y=coordinates[1])
-
+
elif self.mouse['use'] == 'drawRegion':
coordinatesBegin = self.Pixel2Cell(self.mouse['begin'])
-
+
if coordinatesBegin[0] < coordinates[0]:
west = coordinatesBegin[0]
east = coordinates[0]
@@ -1423,7 +1424,7 @@
# redraw map
self.UpdateMap(render = False)
-
+
# TODO: decide which coordinates to send (e, n, mouse['begin'], mouse['end'])
self.mouseLeftUp.emit(x=coordinates[0], y=coordinates[1])
@@ -1432,7 +1433,7 @@
"""
Debug.msg (5, "BufferedWindow.OnButtonDClick(): use=%s" % \
self.mouse["use"])
-
+
screenCoords = event.GetPosition()
if self.mouse['use'] == 'pointer':
@@ -1441,7 +1442,7 @@
if idlist:
self.dragid = idlist[0]
self.overlayActivated.emit(overlayId=self.dragid)
-
+
coords = self.Pixel2Cell(screenCoords)
self.mouseDClick.emit(x=coords[0], y=coords[1])
@@ -1450,45 +1451,45 @@
"""
Debug.msg (5, "BufferedWindow.OnRightDown(): use=%s" % \
self.mouse["use"])
-
+
if hasattr(self, "digit"):
self._onRightDown(event)
-
+
event.Skip()
-
+
def OnRightUp(self, event):
"""Right mouse button released
"""
Debug.msg (5, "BufferedWindow.OnRightUp(): use=%s" % \
self.mouse["use"])
-
+
if hasattr(self, "digit"):
self._onRightUp(event)
-
+
self.redrawAll = True
self.Refresh()
-
+
event.Skip()
-
+
def OnMiddleDown(self, event):
"""Middle mouse button pressed
"""
if not event:
return
-
+
self.mouse['begin'] = event.GetPositionTuple()[:]
-
+
def OnMiddleUp(self, event):
"""Middle mouse button released
"""
self.mouse['end'] = event.GetPositionTuple()[:]
-
+
# set region in zoom or pan
begin = self.mouse['begin']
end = self.mouse['end']
-
+
self.Zoom(begin, end, 0) # no zoom
-
+
# redraw map
self.UpdateMap(render = True)
@@ -1506,7 +1507,7 @@
if self.mouse["use"] == "pointer" and \
hasattr(self, "digit"):
self._onMouseMoving(event)
-
+
event.Skip()
def OnCopyCoordinates(self, event):
@@ -1519,7 +1520,7 @@
do.SetText(str(e) + delim + str(n))
wx.TheClipboard.SetData(do)
wx.TheClipboard.Close()
-
+
def ClearLines(self, pdc = None):
"""Clears temporary drawn lines from PseudoDC
"""
@@ -1530,23 +1531,23 @@
pdc.RemoveId(self.lineid)
except:
pass
-
+
try:
pdc.ClearId(self.plineid)
pdc.RemoveId(self.plineid)
except:
pass
-
+
Debug.msg(4, "BufferedWindow.ClearLines(): lineid=%s, plineid=%s" %
(self.lineid, self.plineid))
-
+
return True
def Pixel2Cell(self, xyCoords):
"""Convert image coordinates to real word coordinates
-
+
:param xyCoords: image coordinates
-
+
:return: easting, northing
:return: None on error
"""
@@ -1555,20 +1556,20 @@
y = int(xyCoords[1])
except:
return None
-
+
if self.Map.region["ewres"] > self.Map.region["nsres"]:
res = self.Map.region["ewres"]
else:
res = self.Map.region["nsres"]
-
+
w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
-
+
east = w + x * res
north = n - y * res
-
+
return (east, north)
-
+
def Cell2Pixel(self, enCoords):
"""Convert real word coordinates to image coordinates
"""
@@ -1577,18 +1578,18 @@
north = float(enCoords[1])
except:
return None
-
+
if self.Map.region["ewres"] > self.Map.region["nsres"]:
res = self.Map.region["ewres"]
else:
res = self.Map.region["nsres"]
-
+
w = self.Map.region["center_easting"] - (self.Map.width / 2) * res
n = self.Map.region["center_northing"] + (self.Map.height / 2) * res
-
+
x = (east - w) / res
y = (n - north) / res
-
+
return (x, y)
def Zoom(self, begin, end, zoomtype):
@@ -1597,7 +1598,7 @@
x1, y1 = begin
x2, y2 = end
newreg = {}
-
+
# threshold - too small squares do not make sense
# can only zoom to windows of > 5x5 screen pixels
if abs(x2-x1) > 5 and abs(y2-y1) > 5 and zoomtype != 0:
@@ -1605,12 +1606,12 @@
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
-
+
# zoom in
if zoomtype > 0:
newreg['w'], newreg['n'] = self.Pixel2Cell((x1, y1))
newreg['e'], newreg['s'] = self.Pixel2Cell((x2, y2))
-
+
# zoom out
elif zoomtype < 0:
newreg['w'], newreg['n'] = self.Pixel2Cell((-x1 * 2, -y1 * 2))
@@ -1628,17 +1629,17 @@
newreg['w'], newreg['n'] = self.Pixel2Cell((dx, dy))
newreg['e'], newreg['s'] = self.Pixel2Cell((self.Map.width + dx,
self.Map.height + dy))
-
+
# if new region has been calculated, set the values
if newreg != {}:
# LL locations
if self.Map.projinfo['proj'] == 'll':
self.Map.region['n'] = min(self.Map.region['n'], 90.0)
self.Map.region['s'] = max(self.Map.region['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
@@ -1649,17 +1650,17 @@
else:
for k in ('n', 's', 'e', 'w'):
self.Map.region[k] = newreg[k]
-
+
if hasattr(self, "digit") and \
hasattr(self, "moveInfo"):
self._zoom(None)
-
+
self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
self.Map.region['e'], self.Map.region['w'])
-
+
if self.redrawAll is False:
self.redrawAll = True
-
+
def ZoomBack(self):
"""Zoom to previous extents in zoomhistory list
@@ -1669,7 +1670,7 @@
Debug.msg(4, "BufferedWindow.ZoomBack(): hist)=%s" % self.zoomhistory)
zoom = list()
-
+
if len(self.zoomhistory) > 1:
self.zoomhistory.pop()
zoom = self.zoomhistory[-1]
@@ -1703,17 +1704,17 @@
"""
removed = None
self.zoomhistory.append((n,s,e,w))
-
+
if len(self.zoomhistory) > 10:
removed = self.zoomhistory.pop(0)
-
+
if removed:
Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s, removed=%s" %
(self.zoomhistory, removed))
else:
Debug.msg(4, "BufferedWindow.ZoomHistory(): hist=%s" %
(self.zoomhistory))
-
+
# update toolbar
if len(self.zoomhistory) > 1:
self.zoomHistoryAvailable.emit()
@@ -1721,7 +1722,7 @@
self.zoomHistoryUnavailable.emit()
self.zoomChanged.emit()
-
+
return removed
def InitZoomHistory(self):
@@ -1748,7 +1749,7 @@
def ResetZoomHistory(self):
"""Reset zoom history"""
self.zoomhistory = list()
-
+
def ZoomToMap(self, layers = None, ignoreNulls = False, render = True):
"""Set display extents to match selected raster
or vector map(s).
@@ -1763,7 +1764,7 @@
if not layers:
return
-
+
rast = []
rast3d = None
vect = []
@@ -1786,17 +1787,17 @@
elif l.type == 'rgb':
for rname in l.GetName().splitlines():
rast.append(rname)
-
+
if not updated:
self.Map.GetRegion(rast=rast,
rast3d=rast3d,
vect=vect,
zoom=ignoreNulls,
update=True)
-
+
self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
self.Map.region['e'], self.Map.region['w'])
-
+
if render:
self.UpdateMap()
@@ -1805,10 +1806,10 @@
settings (set with g.region)
"""
self.Map.region = self.Map.GetRegion()
-
+
self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
self.Map.region['e'], self.Map.region['w'])
-
+
self.UpdateMap()
def ZoomToDefault(self):
@@ -1819,14 +1820,14 @@
self.ZoomHistory(self.Map.region['n'], self.Map.region['s'],
self.Map.region['e'], self.Map.region['w'])
-
+
self.UpdateMap()
def GoTo(self, e, n):
region = self.Map.GetCurrentRegion()
region['center_easting'], region['center_northing'] = e, n
-
+
dn = (region['nsres'] * region['rows']) / 2.
region['n'] = region['center_northing'] + dn
region['s'] = region['center_northing'] - dn
@@ -1838,9 +1839,9 @@
# add to zoom history
self.ZoomHistory(region['n'], region['s'],
- region['e'], region['w'])
+ region['e'], region['w'])
self.UpdateMap()
-
+
def DisplayToWind(self):
"""Set computational region (WIND file) to match display
extents
@@ -1848,7 +1849,7 @@
tmpreg = os.getenv("GRASS_REGION")
if tmpreg:
del os.environ["GRASS_REGION"]
-
+
# We ONLY want to set extents here. Don't mess with resolution. Leave that
# for user to set explicitly with g.region
new = self.Map.AlignResolution()
@@ -1861,12 +1862,12 @@
w = new['w'],
rows = int(new['rows']),
cols = int(new['cols']))
-
+
if tmpreg:
os.environ["GRASS_REGION"] = tmpreg
-
+
self.UpdateMap(render = False)
-
+
def SetRegion(self, zoomOnly=True):
"""Set display extents/compulational region from named region
file.
@@ -1880,24 +1881,24 @@
dlg = SavedRegion(parent = self,
title = label,
loadsave = 'load')
-
+
if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
dlg.Destroy()
return
-
+
region = dlg.GetName()
if not grass.find_file(name = region, element = 'windows')['name']:
GError(parent = self,
message = _("Region <%s> not found. Operation canceled.") % region)
dlg.Destroy()
return
-
+
dlg.Destroy()
-
+
if zoomOnly:
self.Map.GetRegion(regionName = region,
update = True)
-
+
self.ZoomHistory(self.Map.region['n'],
self.Map.region['s'],
self.Map.region['e'],
@@ -1907,7 +1908,7 @@
RunCommand('g.region',
parent = self,
region = region)
-
+
self.UpdateMap()
def SaveRegion(self, display = True):
@@ -1920,12 +1921,12 @@
title = _("Save display extents to region file")
else:
title = _("Save computational region to region file")
-
+
dlg = SavedRegion(parent = self, title = title, loadsave = 'save')
if dlg.ShowModal() == wx.ID_CANCEL or not dlg.GetName():
dlg.Destroy()
return
-
+
# test to see if it already exists and ask permission to overwrite
if grass.find_file(name = dlg.GetName(), element = 'windows')['name']:
overwrite = wx.MessageBox(parent = self,
@@ -1935,17 +1936,17 @@
if overwrite != wx.YES:
dlg.Destroy()
return
-
+
if display:
self._saveDisplayRegion(dlg.GetName())
else:
self._saveCompRegion(dlg.GetName())
-
+
dlg.Destroy()
def _saveCompRegion(self, name):
"""Save region settings to region file
-
+
:param name: region name
"""
RunCommand('g.region',
@@ -1953,18 +1954,18 @@
parent = self,
flags = 'u',
save = name)
-
+
def _saveDisplayRegion(self, name):
"""Save display extents to region file
-
+
:param name: region name
"""
new = self.Map.GetCurrentRegion()
-
+
tmpreg = os.getenv("GRASS_REGION")
if tmpreg:
del os.environ["GRASS_REGION"]
-
+
RunCommand('g.region',
overwrite = True,
parent = self,
@@ -1976,15 +1977,15 @@
rows = int(new['rows']),
cols = int(new['cols']),
save = name)
-
+
if tmpreg:
os.environ["GRASS_REGION"] = tmpreg
-
+
def Distance(self, beginpt, endpt, screen = True):
"""Calculates distance
-
+
Ctypes required for LL-locations
-
+
:param beginpt: first point
:param endpt: second point
:param screen: True for screen coordinates otherwise EN
@@ -1995,15 +1996,15 @@
else:
e1, n1 = beginpt
e2, n2 = endpt
-
+
dEast = (e2 - e1)
dNorth = (n2 - n1)
-
+
if self.Map.projinfo['proj'] == 'll' and haveCtypes:
dist = gislib.G_distance(e1, n1, e2, n2)
else:
dist = math.sqrt(math.pow((dEast), 2) + math.pow((dNorth), 2))
-
+
return (dist, (dEast, dNorth))
def GetMap(self):
@@ -2013,15 +2014,14 @@
def RegisterGraphicsToDraw(self, graphicsType, setStatusFunc=None, drawFunc=None,
mapCoords=True):
"""This method registers graphics to draw.
-
+
:param type: (string) - graphics type: "point", "line" or "rectangle"
:param setStatusFunc: function called before drawing each item
Status function should be in this form:
setStatusFunc(item, itemOrderNum)
item passes instance of GraphicsSetItem
- which will be drawn
- itemOrderNum number of item in drawing
- order (from O)
+ which will be drawn itemOrderNum number of item
+ in drawing order (from O)
Hidden items are also counted in drawing order.
:type setStatusFunc: function
:param drawFunc: defines own function for drawing, if function
@@ -2032,25 +2032,25 @@
:return: reference to GraphicsSet, which was added.
"""
- item = GraphicsSet(parentMapWin=self,
- graphicsType=graphicsType,
- setStatusFunc=setStatusFunc,
+ item = GraphicsSet(parentMapWin=self,
+ graphicsType=graphicsType,
+ setStatusFunc=setStatusFunc,
drawFunc=drawFunc,
mapCoords=mapCoords)
self.graphicsSetList.append(item)
-
+
return item
def UnregisterGraphicsToDraw(self, item):
"""Unregisteres GraphicsSet instance
-
+
:param item: (GraphicsSetItem) - item to unregister
-
+
:return: True - if item was unregistered
:return: False - if item was not found
- """
+ """
if item in self.graphicsSetList:
self.graphicsSetList.remove(item)
return True
-
+
return False
Modified: grass/trunk/gui/wxpython/mapwin/graphics.py
===================================================================
--- grass/trunk/gui/wxpython/mapwin/graphics.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/mapwin/graphics.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -102,10 +102,12 @@
if label is None:
self.properties["text"] = None
else:
- self.properties["text"]['coords'] = [coords[0] + size, coords[1] + size, size, size]
+ self.properties["text"]['coords'] = [coords[0] + size,
+ coords[1] + size,
+ size, size]
self.properties["text"]['color'] = self.parentMapWin.pen.GetColour()
self.properties["text"]['text'] = label
-
+
self.drawFunc(pdc=pdc, drawid=item.GetId(),
coords=coords,
text=self.properties["text"],
@@ -124,7 +126,7 @@
self.drawFunc(pdc=pdc, pen=pen,
coords=coords, drawid=item.GetId())
-
+
elif self.graphicsType == "rectangle":
if item.GetPropertyVal("penName"):
pen = self.pens[item.GetPropertyVal("penName")]
@@ -149,7 +151,7 @@
else:
coords = item.GetCoords()
- self.drawFunc(pdc=pdc, pen=pen,
+ self.drawFunc(pdc=pdc, pen=pen,
coords=coords, drawid=item.GetId())
itemOrderNum += 1
@@ -159,10 +161,12 @@
Added item is put to the last place in drawing order.
Could be 'point' or 'line' according to graphicsType.
- :param coords: - list of east, north coordinates (double) of item
- Example: point: [1023, 122]
- line: [[10, 12],[20,40],[23, 2334]]
- rectangle: [[10, 12], [33, 45]]
+ :param coords: list of east, north coordinates (double) of item.
+ Example:
+
+ * point: [1023, 122]
+ * line: [[10, 12],[20,40],[23, 2334]]
+ * rectangle: [[10, 12], [33, 45]]
:param penName: the 'default' pen is used if is not defined
:type penName: str
:param label: label, which will be drawn with point. It is
@@ -174,7 +178,8 @@
:type hide: bool
:return: (GraphicsSetItem) - added item reference
"""
- item = GraphicsSetItem(coords=coords, penName=penName, label=label, hide=hide)
+ item = GraphicsSetItem(coords=coords, penName=penName, label=label,
+ hide=hide)
self.itemsList.append(item)
return item
@@ -385,9 +390,11 @@
"""Set coordinates of item
:param coords: list of east, north coordinates (double) of item
- Example: point: [1023, 122]
- line: [[10, 12],[20,40],[23, 2334]]
- rectangle: [[10, 12], [33, 45]]
+ Example:
+
+ * point: [1023, 122]
+ * line: [[10, 12],[20,40],[23, 2334]]
+ * rectangle: [[10, 12], [33, 45]]
"""
self.coords = coords
Modified: grass/trunk/gui/wxpython/nviz/workspace.py
===================================================================
--- grass/trunk/gui/wxpython/nviz/workspace.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/nviz/workspace.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -20,14 +20,15 @@
from core.utils import _
try:
- from nviz import wxnviz
+ from nviz import wxnviz
except ImportError:
wxnviz = None
+
class NvizSettings(object):
def __init__(self):
pass
-
+
def SetConstantDefaultProp(self):
"""Set default constant data properties"""
data = dict()
@@ -37,14 +38,14 @@
data['color'] = color
return data
-
- def SetSurfaceDefaultProp(self, data = None):
+
+ def SetSurfaceDefaultProp(self, data=None):
"""Set default surface data properties"""
if not data:
data = dict()
for sec in ('attribute', 'draw', 'mask', 'position'):
data[sec] = {}
-
+
#
# attributes
#
@@ -54,12 +55,13 @@
subkey=attrb).iteritems():
data['attribute'][attrb][key] = value
data['attribute'][attrb]['update'] = None
-
+
#
# draw
#
data['draw']['all'] = False # apply only for current surface
- for control, value in UserSettings.Get(group='nviz', key='surface', subkey='draw').iteritems():
+ for control, value in UserSettings.Get(group='nviz', key='surface',
+ subkey='draw').iteritems():
if control[:3] == 'res':
if 'resolution' not in data['draw']:
data['draw']['resolution'] = {}
@@ -67,7 +69,7 @@
data['draw']['resolution']['update'] = None
data['draw']['resolution'][control[4:]] = value
continue
-
+
if control == 'wire-color':
value = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
elif control in ('mode', 'style', 'shading'):
@@ -77,21 +79,21 @@
data['draw'][control] = { 'value' : value }
data['draw'][control]['update'] = None
-
+
value, desc = self.GetDrawMode(UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'mode']),
UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'style']),
UserSettings.Get(group='nviz', key='surface', subkey=['draw', 'shading']))
-
+
data['draw']['mode'] = { 'value' : value,
- 'desc' : desc,
+ 'desc' : desc,
'update': None }
# position
for coord in ('x', 'y', 'z'):
data['position'][coord] = UserSettings.Get(group='nviz', key='surface', subkey=['position', coord])
data['position']['update'] = None
-
+
return data
-
+
def SetVolumeDefaultProp(self):
"""Set default volume data properties"""
data = dict()
@@ -99,7 +101,7 @@
data[sec] = dict()
for sec in ('isosurface', 'slice'):
data[sec] = list()
-
+
#
# draw
#
@@ -107,7 +109,7 @@
if control == 'shading':
sel = UserSettings.Get(group='nviz', key='volume', subkey=['draw', 'shading'])
value, desc = self.GetDrawMode(shade=sel, string=False)
-
+
data['draw']['shading'] = {}
data['draw']['shading']['isosurface'] = { 'value' : value,
'desc' : desc['shading'] }
@@ -132,7 +134,7 @@
if 'update' not in data['draw'][control]:
data['draw'][control]['update'] = None
-
+
#
# isosurface attributes
#
@@ -141,9 +143,9 @@
for key, value in UserSettings.Get(group='nviz', key='volume',
subkey=attrb).iteritems():
data['attribute'][attrb][key] = value
-
+
return data
-
+
def SetIsosurfaceDefaultProp(self):
"""Set default isosurface properties"""
data = dict()
@@ -152,59 +154,59 @@
data[attr]['update'] = None
if attr == 'inout':
data[attr]['value'] = 0
- continue
+ continue
for key, value in UserSettings.Get(group = 'nviz', key = 'volume',
subkey = attr).iteritems():
data[attr][key] = value
return data
-
+
def SetSliceDefaultProp(self):
"""Set default slice properties"""
data = dict()
- data['position'] = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'volume',
+ data['position'] = copy.deepcopy(UserSettings.Get(group='nviz', key='volume',
subkey = 'slice_position'))
data['position']['update'] = None
-
- data['transp'] = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'volume',
- subkey = 'transp'))
+
+ data['transp'] = copy.deepcopy(UserSettings.Get(group='nviz', key='volume',
+ subkey='transp'))
return data
-
- def SetVectorDefaultProp(self, data = None):
+
+ def SetVectorDefaultProp(self, data=None):
"""Set default vector data properties"""
if not data:
data = dict()
for sec in ('lines', 'points'):
data[sec] = {}
-
+
self.SetVectorLinesDefaultProp(data['lines'])
self.SetVectorPointsDefaultProp(data['points'])
return data
-
+
def SetVectorLinesDefaultProp(self, data):
"""Set default vector properties -- lines"""
# width
- data['width'] = {'value' : UserSettings.Get(group='nviz', key='vector',
- subkey=['lines', 'width']) }
-
+ data['width'] = {'value': UserSettings.Get(group='nviz', key='vector',
+ subkey=['lines', 'width'])}
+
# color
value = UserSettings.Get(group='nviz', key='vector',
subkey=['lines', 'color'])
color = str(value[0]) + ':' + str(value[1]) + ':' + str(value[2])
- data['color'] = { 'value' : color }
+ data['color'] = {'value': color}
# mode
if UserSettings.Get(group='nviz', key='vector',
subkey=['lines', 'flat']):
type = 'flat'
-
+
else:
type = 'surface'
-
+
data['mode'] = {}
data['mode']['type'] = type
data['mode']['update'] = None
-
+
# height
data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
subkey=['lines', 'height']) }
@@ -219,7 +221,7 @@
if 'object' in data:
for attrb in ('color', 'width', 'mode', 'height', 'thematic'):
data[attrb]['update'] = None
-
+
def SetVectorPointsDefaultProp(self, data):
"""Set default vector properties -- points"""
# size
@@ -243,11 +245,11 @@
# mode
data['mode'] = { 'type' : 'surface'}
## 'surface' : '', }
-
+
# height
data['height'] = { 'value' : UserSettings.Get(group='nviz', key='vector',
subkey=['points', 'height']) }
-
+
data['thematic'] = {'rgbcolumn' : UserSettings.Get(group='nviz', key='vector',
subkey=['points', 'rgbcolumn']),
'sizecolumn' : UserSettings.Get(group='nviz', key='vector',
@@ -259,7 +261,7 @@
for attrb in ('size', 'width', 'marker',
'color', 'height', 'thematic'):
data[attrb]['update'] = None
-
+
def GetDrawMode(self, mode=None, style=None, shade=None, string=False):
"""Get surface draw mode (value) from description/selection
@@ -267,11 +269,11 @@
:param style:
:param shade:
:param string: if True input parameters are strings otherwise
- selections
+ selections
"""
if not wxnviz:
return None
-
+
value = 0
desc = {}
@@ -289,7 +291,7 @@
value |= wxnviz.DM_GRID_WIRE
else: # surface
value |= wxnviz.DM_GRID_SURF
-
+
if shade is not None:
if shade == 'flat':
value |= wxnviz.DM_FLAT
@@ -325,27 +327,35 @@
else: # surface
value |= wxnviz.DM_GOURAUD
desc['shading'] = 'gouraud'
-
+
return (value, desc)
-
+
def SetDecorDefaultProp(self, type):
"""Set default arrow properties
"""
data = {}
-
+
# arrow
if type == 'arrow':
- data['arrow'] = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'arrow'))
+ data['arrow'] = copy.deepcopy(UserSettings.Get(group='nviz',
+ key='arrow'))
data['arrow']['color'] = "%d:%d:%d" % (
- UserSettings.Get(group = 'nviz', key = 'arrow', subkey = 'color')[:3])
- data['arrow'].update(copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'arrow', internal = True)))
+ UserSettings.Get(group='nviz', key='arrow',
+ subkey='color')[:3])
+ data['arrow'].update(copy.deepcopy(UserSettings.Get(group='nviz',
+ key='arrow',
+ internal=True)))
data['arrow']['show'] = False
-
+
# arrow
if type == 'scalebar':
- data['scalebar'] = copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'scalebar'))
+ data['scalebar'] = copy.deepcopy(UserSettings.Get(group='nviz',
+ key='scalebar'))
data['scalebar']['color'] = "%d:%d:%d" % (
- UserSettings.Get(group = 'nviz', key = 'scalebar', subkey = 'color')[:3])
- data['scalebar'].update(copy.deepcopy(UserSettings.Get(group = 'nviz', key = 'scalebar', internal = True)))
+ UserSettings.Get(group='nviz', key='scalebar',
+ subkey='color')[:3])
+ data['scalebar'].update(copy.deepcopy(UserSettings.Get(group='nviz',
+ key='scalebar',
+ internal=True)))
data['scalebar']['id'] = 0
return data
Modified: grass/trunk/gui/wxpython/rlisetup/wizard.py
===================================================================
--- grass/trunk/gui/wxpython/rlisetup/wizard.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/rlisetup/wizard.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -530,13 +530,14 @@
"""
next = wx.FindWindowById(wx.ID_FORWARD)
next.Enable(self.CheckInput())
- wx.CallAfter(wx.FindWindowById(wx.ID_FORWARD).Enable, self.CheckInput())
+ wx.CallAfter(wx.FindWindowById(wx.ID_FORWARD).Enable,
+ self.CheckInput())
def CheckInput(self):
"""Check input fields.
:return: True if configuration file is given and raster xor vector map,
- False otherwise
+ False otherwise
"""
#R#return bool(self.conf_name and (bool(self.rast) != bool(self.vect)))
return bool(self.conf_name and bool(self.rast))
@@ -1392,7 +1393,7 @@
gtype = self.parent.drawunits.drawtype
self.mapPanel = RLiSetupMapPanel(self,
- samplingType=self.parent.samplingareapage.samplingtype,
+ samplingType=self.parent.samplingareapage.samplingtype,
)
if gtype == 'circle':
self.mapPanel.afterCircleDrawn.connect(self.SampleFrameChanged)
@@ -1639,8 +1640,8 @@
flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
self.sizer.Add(item=self.unitsmoretxt2, border=5, pos=(11, 1),
flag=wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL | wx.ALL)
-
+
def OnEnterPage(self, event):
"""Insert values into text controls for summary of location
creation options
Modified: grass/trunk/gui/wxpython/web_services/widgets.py
===================================================================
--- grass/trunk/gui/wxpython/web_services/widgets.py 2014-09-12 20:36:27 UTC (rev 61885)
+++ grass/trunk/gui/wxpython/web_services/widgets.py 2014-09-12 22:14:55 UTC (rev 61886)
@@ -58,7 +58,7 @@
def __init__(self, parent, web_service, **kwargs):
"""Show data from capabilities file.
- Signal: capParsed - this signal is emitted when capabilities file is downloaded
+ Signal: capParsed - this signal is emitted when capabilities file is downloaded
(after ConnectToServer method was called)
:param parent: parent widget
@@ -68,7 +68,7 @@
self.parent = parent
self.ws = web_service
-
+
self.capParsed = Signal('WSPanel.capParsed')
# stores widgets, which represents parameters/flags of d.wms
@@ -93,14 +93,14 @@
self.drv_info = WMSDriversInfo()
self.drv_props = self.drv_info.GetDrvProperties(self.ws)
- self.ws_drvs = {
+ self.ws_drvs = {
'WMS_1.1.1' : {
- 'cmd' : ['wms_version=1.1.1',
+ 'cmd' : ['wms_version=1.1.1',
'driver=WMS_GRASS'],
'cap_parser' : lambda temp_file : WMSCapabilities(temp_file, '1.1.1'),
},
'WMS_1.3.0' : {
- 'cmd' : ['wms_version=1.3.0',
+ 'cmd' : ['wms_version=1.3.0',
'driver=WMS_GRASS'],
'cap_parser' : lambda temp_file : WMSCapabilities(temp_file, '1.3.0'),
},
@@ -144,41 +144,41 @@
def _requestPage(self):
"""Create request page"""
self.req_page_panel = wx.Panel(parent = self, id = wx.ID_ANY)
- self.notebook.AddPage(page = self.req_page_panel,
- text=_('Request'),
+ self.notebook.AddPage(page = self.req_page_panel,
+ text=_('Request'),
name = 'request')
# list of layers
self.layersBox = wx.StaticBox(parent = self.req_page_panel, id = wx.ID_ANY,
label=_("List of layers "))
- style = wx.TR_DEFAULT_STYLE | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT
- if self.drv_props['req_multiple_layers']:
+ style = wx.TR_DEFAULT_STYLE | wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT
+ if self.drv_props['req_multiple_layers']:
style = style | wx.TR_MULTIPLE
if 'WMS' not in self.ws:
style = style | wx.TR_HIDE_ROOT
- self.list = LayersList(parent = self.req_page_panel,
- web_service = self.ws,
+ self.list = LayersList(parent = self.req_page_panel,
+ web_service = self.ws,
style = style)
- self.params['format'] = None
+ self.params['format'] = None
self.params['srs'] = None
if 'srs' not in self.drv_props['ignored_params']:
projText = wx.StaticText(parent = self.req_page_panel, id = wx.ID_ANY, label = _("Source projection:"))
self.params['srs'] = wx.Choice(parent = self.req_page_panel, id = wx.ID_ANY)
-
+
self.list.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnListSelChanged)
-
+
# layout
self.req_page_sizer = wx.BoxSizer(wx.VERTICAL)
-
+
layersSizer = wx.StaticBoxSizer(self.layersBox, wx.HORIZONTAL)
layersSizer.Add(item = self.list, proportion = 1,
flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-
+
self.req_page_sizer.Add(item = layersSizer, proportion = 1,
flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
@@ -187,17 +187,17 @@
if self.params['format'] is not None:
self.source_sizer.Add(item = self.params['format'],
flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-
+
if self.params['srs'] is not None:
self.source_sizer.Add(item = projText, flag = wx.ALIGN_CENTER_VERTICAL | wx.ALL, border = 5)
self.source_sizer.Add(item = self.params['srs'],
flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT | wx.TOP | wx.BOTTOM, border = 5)
-
+
self.req_page_sizer.Add(item = self.source_sizer,
flag = wx.LEFT | wx.RIGHT | wx.BOTTOM | wx.EXPAND, border = 5)
-
+
self.req_page_panel.SetSizer(self.req_page_sizer)
-
+
def enableButtons(self, enable = True):
"""Enable/disable up, down, buttons
"""
@@ -210,8 +210,8 @@
#TODO parse maxcol, maxrow, settings from d.wms module?
#TODO OnEarth driver - add selection of time
adv_setts_panel = wx.Panel(parent = self, id = wx.ID_ANY)
- self.notebook.AddPage(page = adv_setts_panel,
- text=_('Advanced request settings'),
+ self.notebook.AddPage(page = adv_setts_panel,
+ text=_('Advanced request settings'),
name = 'adv_req_setts')
labels = {}
@@ -219,7 +219,7 @@
if 'WMS' in self.ws:
labels['l_order'] = wx.StaticBox(parent = adv_setts_panel, id = wx.ID_ANY,
label = _("Order of layers in raster"))
- self.l_odrder_list = wx.ListBox(adv_setts_panel, id = wx.ID_ANY, choices = [],
+ self.l_odrder_list = wx.ListBox(adv_setts_panel, id = wx.ID_ANY, choices = [],
style = wx.LB_SINGLE|wx.LB_NEEDED_SB)
self.btnUp = wx.Button(adv_setts_panel, id = wx.ID_ANY, label = _("Up"))
self.btnDown = wx.Button(adv_setts_panel, id = wx.ID_ANY, label = _("Down"))
@@ -274,35 +274,35 @@
# layout
border = wx.BoxSizer(wx.VERTICAL)
-
+
if 'WMS' in self.ws:
boxSizer = wx.StaticBoxSizer(labels['l_order'], wx.VERTICAL)
gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
- gridSizer.Add(self.l_odrder_list,
- pos = (0,0),
- span = (4, 1),
- flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
+ gridSizer.Add(self.l_odrder_list,
+ pos = (0,0),
+ span = (4, 1),
+ flag = wx.ALIGN_CENTER_VERTICAL|wx.EXPAND,
border = 0)
-
+
gridSizer.Add(self.btnUp,
- pos = (0,1),
- flag = wx.ALIGN_CENTER_VERTICAL,
+ pos = (0,1),
+ flag = wx.ALIGN_CENTER_VERTICAL,
border = 0)
- gridSizer.Add(self.btnDown,
- pos = (1,1),
+ gridSizer.Add(self.btnDown,
+ pos = (1,1),
flag = wx.ALIGN_CENTER_VERTICAL,
border = 0)
-
+
gridSizer.AddGrowableCol(0)
boxSizer.Add(gridSizer,
flag = wx.EXPAND | wx.ALL,
border = 5)
border.Add(item = boxSizer,
- flag = wx.LEFT | wx.RIGHT | wx.UP | wx.EXPAND,
+ flag = wx.LEFT | wx.RIGHT | wx.UP | wx.EXPAND,
border = 5)
gridSizer = wx.GridBagSizer (hgap = 3, vgap = 3)
@@ -338,7 +338,7 @@
gridSizer.AddGrowableCol(0)
border.Add(item = gridSizer,
- flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
+ flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
border = 5)
if self.params['urlparams']:
@@ -357,7 +357,7 @@
pos = (row, 1))
border.Add(item = gridSizer,
- flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
+ flag = wx.LEFT | wx.RIGHT | wx.TOP | wx.EXPAND,
border = 5)
adv_setts_panel.SetSizer(border)
@@ -368,9 +368,9 @@
if self.l_odrder_list.GetSelections():
pos = self.l_odrder_list.GetSelection()
if pos:
- self.sel_layers.insert(pos - 1, self.sel_layers.pop(pos))
+ self.sel_layers.insert(pos - 1, self.sel_layers.pop(pos))
if pos > 0:
- self._updateLayerOrderList(selected = (pos - 1))
+ self._updateLayerOrderList(selected = (pos - 1))
else:
self._updateLayerOrderList(selected = 0)
@@ -382,7 +382,7 @@
if pos != len(self.sel_layers) - 1:
self.sel_layers.insert(pos + 1, self.sel_layers.pop(pos))
if pos < len(self.sel_layers) -1:
- self._updateLayerOrderList(selected = (pos + 1))
+ self._updateLayerOrderList(selected = (pos + 1))
else:
self._updateLayerOrderList(selected = len(self.sel_layers) -1)
@@ -409,8 +409,8 @@
else:
self.enableButtons(True)
if selected is not None:
- self.l_odrder_list.SetSelection(selected)
- self.l_odrder_list.EnsureVisible(selected)
+ self.l_odrder_list.SetSelection(selected)
+ self.l_odrder_list.EnsureVisible(selected)
def OnTransparent(self, event):
checked = event.IsChecked()
@@ -527,7 +527,7 @@
def UpdateWidgetsByCmd(self, cmd):
"""Update panel widgets accordnig to passed cmd tuple
-
+
:param cmd: cmd in tuple
"""
@@ -556,7 +556,7 @@
for i in range(len(layers)):
l_st_list.append({'style' : styles[i],
'layer' : layers[i]})
-
+
# WMS standard - first layer in params is most bottom...
# therefore layers order need to be reversed
l_st_list = [l for l in reversed(l_st_list)]
@@ -573,7 +573,7 @@
for p, v in params.iteritems():
if self.params[p]:
self.params[p].SetStringSelection(v)
-
+
for p, conv_f in [('urlparams', None), ('maxcols', int), ('maxrows', int)]:
if dcmd.has_key(p):
v = dcmd[p]
@@ -592,7 +592,7 @@
if len(bgcolor) == 8 and \
'0x' == bgcolor[:2]:
- colour= '#' + bgcolor[2:]
+ colour = '#' + bgcolor[2:]
self.params['bgcolor'].SetColour(colour)
def IsConnected(self):
@@ -606,10 +606,10 @@
self.capParsed.emit(error_msg=error_msg)
def CreateCmd(self):
- """Create d.wms cmd from values of panels widgets
+ """Create d.wms cmd from values of panels widgets
:return: cmd list
- :return: None if required widgets do not have selected/filled values.
+ :return: None if required widgets do not have selected/filled values.
"""
# check required widgets
@@ -620,8 +620,8 @@
lcmd = self.ws_cmdl
lcmd = ['d.wms'] + lcmd
- layers="layers="
- styles='styles='
+ layers = "layers="
+ styles = 'styles='
first = True
# WMS standard - first layer in params is most bottom...
@@ -631,7 +631,7 @@
layers += ','
styles += ','
first = False
- layers += layer['name']
+ layers += layer['name']
if layer['style'] is not None:
styles += layer['style']['name']
@@ -659,7 +659,7 @@
c = self.params['bgcolor'].GetColour()
hex_color = wx.Colour(c[0], c[1], c[2]).GetAsString(wx.C2S_HTML_SYNTAX)
- lcmd.append("bgcolor=" + '0x' + hex_color[1:])
+ lcmd.append("bgcolor=" + '0x' + hex_color[1:])
lcmd.append("map=" + self.o_layer_name)
@@ -683,7 +683,7 @@
else:
self.sel_layers = curr_sel_ls
- # update projection
+ # update projection
self.projs_list = []
projs_list = []
@@ -716,7 +716,6 @@
self.projs_list = sorted(self.projs_list)
self.params['srs'].SetItems(self.projs_list)
-
if cur_sel:
self.params['srs'].SetStringSelection(cur_sel)
else:
@@ -764,16 +763,17 @@
self.req_page_sizer.Detach(self.params['format'])
self.params['format'].Destroy()
if len(self.formats_list) > 0:
- self.params['format'] = wx.RadioBox(parent = self.req_page_panel, id = wx.ID_ANY,
- label = _("Source image format"), pos = wx.DefaultPosition,
- choices = formats_list, majorDimension = 4,
+ self.params['format'] = wx.RadioBox(parent = self.req_page_panel, id = wx.ID_ANY,
+ label = _("Source image format"), pos = wx.DefaultPosition,
+ choices = formats_list, majorDimension = 4,
style = wx.RA_SPECIFY_COLS)
- self.source_sizer.Insert(item = self.params['format'], before = 2,
- flag = wx.LEFT | wx.RIGHT | wx.BOTTOM, border = 5)
-
- def _getFormats(self, layer = None):
- """Get formats
+ self.source_sizer.Insert(item=self.params['format'], before=2,
+ flag=wx.LEFT | wx.RIGHT | wx.BOTTOM,
+ border=5)
+ def _getFormats(self, layer=None):
+ """Get formats
+
WMS has formats defined generally for whole cap.
In WMTS and NASA OnEarh formats are defined for layer.
"""
@@ -792,7 +792,7 @@
return formats_label
- def _checkImportValues(self,):
+ def _checkImportValues(self,):
"""Check if required widgets are selected/filled
"""
warning_str = ""
@@ -812,12 +812,11 @@
show_war = True
if not self.o_layer_name:
- warning_str += _("Choose output layer name.\n")
+ warning_str += _("Choose output layer name.\n")
show_war = True
if show_war:
- GMessage(parent = self.parent,
- message = warning_str)
+ GMessage(parent=self.parent, message=warning_str)
return False
return True
@@ -840,6 +839,7 @@
"""
return self.ws
+
class LayersList(TreeListCtrl, listmix.ListCtrlAutoWidthMixin):
def __init__(self, parent, web_service, style, pos=wx.DefaultPosition):
"""List of layers and styles available in capabilities file
@@ -848,7 +848,7 @@
self.ws = web_service
TreeListCtrl.__init__(self, parent = parent, id = wx.ID_ANY, style = style)
-
+
# setup mixins
listmix.ListCtrlAutoWidthMixin.__init__(self)
if self.ws != 'OnEarth':
@@ -859,7 +859,7 @@
self.SetMainColumn(0) # column with the tree
self.setResizeColumn(0)
-
+
self.root = None
self.Bind(wx.EVT_TREE_SEL_CHANGING, self.OnListSelChanging)
@@ -873,10 +873,10 @@
if not cap:
return
-
+
def AddLayerChildrenToTree(parent_layer, parent_item):
"""Recursive function which adds all capabilities
- layers/styles to the LayersList.
+ layers/styles to the LayersList.
"""
def gettitle(layer):
"""Helper function"""
@@ -915,9 +915,9 @@
self.SetItemText(style_item, _('style'), 1)
self.SetPyData(style_item, {'type' : 'style',
- 'layer' : layer, # it is parent layer of style
+ 'layer' : layer, # it is parent layer of style
'style' : st})
-
+
self.SetPyData(item, {'type' : 'layer', # is it layer or style?
'layer' : layer, # Layer instance from web_services.cap_interface
'style' : def_st}) # layer can have assigned default style
@@ -929,7 +929,7 @@
addlayer(parent_layer, parent_item)
for layer in parent_layer.GetChildren():
- item = self.AppendItem(parent_item, gettitle(layer))
+ item = self.AppendItem(parent_item, gettitle(layer))
addlayer(layer, item)
AddLayerChildrenToTree(layer, item)
@@ -940,11 +940,11 @@
"""Get selected layers/styles in LayersList
:return: dict with these items:
- 'name' : layer name used for request
- if it is style, it is name of parent layer
- 'title' : layer title
- 'style' : {'name' : 'style name', title : 'style title'}
- 'cap_intf_l' : *Layer instance from web_services.cap_interface
+ * 'name' : layer name used for request
+ if it is style, it is name of parent layer
+ * 'title' : layer title
+ * 'style' : {'name' : 'style name', title : 'style title'}
+ * 'cap_intf_l' : \*Layer instance from web_services.cap_interface
"""
sel_layers = self.GetSelections()
sel_layers_dict = []
@@ -953,7 +953,7 @@
layer = self.GetPyData(s)['layer']
except ValueError:
continue
- sel_layers_dict.append({
+ sel_layers_dict.append({
'name' : layer.GetLayerData('name'),
'title' : layer.GetLayerData('title'),
'style' : self.GetPyData(s)['style'],
@@ -997,7 +997,7 @@
while True:
_selectRequestableChildren(chck_item, items_to_chck, items_to_sel)
if items_to_chck:
- chck_item = items_to_chck.pop()
+ chck_item = items_to_chck.pop()
else:
break
@@ -1005,7 +1005,7 @@
self.SelectItem(items_to_sel.pop(), unselect_others=False)
else:
_emitSelected(self.GetPyData(cur_item)['layer'])
-
+
def GetItemCount(self):
"""Required for listmix.ListCtrlAutoWidthMixin
"""
@@ -1052,14 +1052,14 @@
self.UnselectAll()
- l_st_list = deepcopy(l_st_list)
+ l_st_list = deepcopy(l_st_list)
root_item = self.GetRootItem()
items_to_sel = [None] * len(l_st_list)
checknext(root_item, l_st_list, items_to_sel)
# items are selected according to position in l_st_list
- # to be added to Layers order list in right order
+ # to be added to Layers order list in right order
for i in items_to_sel:
if not i:
continue
@@ -1085,7 +1085,7 @@
self.btnAddDefaultServers = wx.Button(parent=self, id=wx.ID_ANY,
label=_("Add default servers"))
self.btnAddDefaultServers.Bind(wx.EVT_BUTTON, self.OnAddDefaultServers)
-
+
ManageSettingsWidget._layout(self)
self.settingsSizer.Add(item=self.btnAddDefaultServers,
flag=wx.RIGHT,
More information about the grass-commit
mailing list